<?php
/**
* Zend_Sniffs_Strings_DoubleQuoteUsageSniff.
*
* PHP version 5
*
* @category PHP
* @package PHP_CodeSniffer
* @author Juan Sotuyo <juansotuyo@gmail.com>
* @copyright 2010 Juan Sotuyo (Buenos Aires, Argentina)
* @license BSD Licence
* @version 1.0
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
/**
* Zend_Sniffs_Strings_DoubleQuoteUsageSniff.
*
* Makes sure that any use of Double Quotes ("") are warranted.
*
* @category PHP
* @package PHP_CodeSniffer
* @author Juan Sotuyo <juansotuyo@gmail.com>
* @copyright 2010 Juan Sotuyo (Buenos Aires, Argentina)
* @license BSD Licence
* @version Release: 1.2.2
* @link http://pear.php.net/package/PHP_CodeSniffer
*/
class Zend_Sniffs_Strings_DoubleQuoteUsageSniff implements PHP_CodeSniffer_Sniff
{
protected static $allowedChars = array(
'\0',
'\n',
'\r',
'\f',
'\t',
'\v',
'\x',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_CONSTANT_ENCAPSED_STRING,
T_DOUBLE_QUOTED_STRING,
);
}//end register()
/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token
* in the stack passed in $tokens.
*
* @return void
*/
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$string = $tokens[$stackPtr]['content'];
$varFound = false;
// The use of variables in double quoted strings is not allowed.
if ($tokens[$stackPtr]['code'] === T_DOUBLE_QUOTED_STRING) {
$stringTokens = token_get_all('<?php '.$string);
foreach ($stringTokens as $token) {
if (is_array($token) === true && $token[0] === T_VARIABLE) {
$varFound = true;
}
}
}
// Check the var is not in the "${...}" format
$matches = preg_match('/\$\{[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\}/', $string);
if ($matches !== false && $matches > 0) {
$error = 'String "'.$string.'" contains a variable in the format: ${variable} which is not allowed; use no braces or {$var} instead';
$phpcsFile->addError($error, $stackPtr);
}
if ($varFound) {
return;
}
// Are apostrophes included in the string?
if (strstr($string, "'") !== false) {
return;
}
foreach (self::$allowedChars as $char) {
if (strstr($string, $char) !== false) {
return;
}
}
$error = 'String '.$string.' dows not require double quotes; use single quotes instead.';
$phpcsFile->addError($error, $stackPtr);
}//end process()
}//end class
?>