Introducing coding standards validation.

This commit is contained in:
Marcos Schratzenstaller
2019-04-22 17:28:46 -03:00
committed by Nathan Rice
parent 6e40c921ab
commit fd504d41ac
1624 changed files with 190339 additions and 262 deletions
@@ -0,0 +1,73 @@
<?php
/**
* \PHPCompatibility\Sniffs\Keywords\CaseSensitiveKeywordsSniff.
*
* PHP version 5.5
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
namespace PHPCompatibility\Sniffs\Keywords;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
/**
* \PHPCompatibility\Sniffs\Keywords\CaseSensitiveKeywordsSniff.
*
* Prior to PHP 5.5, cases existed where the self, parent, and static keywords
* were treated in a case sensitive fashion.
*
* PHP version 5.5
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
class CaseSensitiveKeywordsSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_SELF,
T_STATIC,
T_PARENT,
);
}
/**
* 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(File $phpcsFile, $stackPtr)
{
if ($this->supportsBelow('5.4') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
$tokenContentLC = strtolower($tokens[$stackPtr]['content']);
if ($tokenContentLC !== $tokens[$stackPtr]['content']) {
$phpcsFile->addError(
'The keyword \'%s\' was treated in a case-sensitive fashion in certain cases in PHP 5.4 or earlier. Use the lowercase version for consistent support.',
$stackPtr,
'NonLowercaseFound',
array($tokenContentLC)
);
}
}
}
@@ -0,0 +1,248 @@
<?php
/**
* \PHPCompatibility\Sniffs\Keywords\ForbiddenNamesAsDeclaredClassSniff.
*
* PHP version 7.0+
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
namespace PHPCompatibility\Sniffs\Keywords;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* \PHPCompatibility\Sniffs\Keywords\ForbiddenNamesAsDeclaredClassSniff.
*
* Prohibits the use of some reserved keywords to name a class, interface, trait or namespace.
* Emits errors for reserved words and warnings for soft-reserved words.
*
* @see http://php.net/manual/en/reserved.other-reserved-words.php
*
* PHP version 7.0+
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
class ForbiddenNamesAsDeclaredSniff extends Sniff
{
/**
* List of tokens which can not be used as class, interface, trait names or as part of a namespace.
*
* @var array
*/
protected $forbiddenTokens = array(
T_NULL => '7.0',
T_TRUE => '7.0',
T_FALSE => '7.0',
);
/**
* T_STRING keywords to recognize as forbidden names.
*
* @var array
*/
protected $forbiddenNames = array(
'null' => '7.0',
'true' => '7.0',
'false' => '7.0',
'bool' => '7.0',
'int' => '7.0',
'float' => '7.0',
'string' => '7.0',
'iterable' => '7.1',
'void' => '7.1',
'object' => '7.2',
);
/**
* T_STRING keywords to recognize as soft reserved names.
*
* Using any of these keywords to name a class, interface, trait or namespace
* is highly discouraged since they may be used in future versions of PHP.
*
* @var array
*/
protected $softReservedNames = array(
'resource' => '7.0',
'object' => '7.0',
'mixed' => '7.0',
'numeric' => '7.0',
);
/**
* Combined list of the two lists above.
*
* Used for quick check whether or not something is a reserved
* word.
* Set from the `register()` method.
*
* @var array
*/
private $allForbiddenNames = array();
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
// Do the list merge only once.
$this->allForbiddenNames = array_merge($this->forbiddenNames, $this->softReservedNames);
$targets = array(
T_CLASS,
T_INTERFACE,
T_TRAIT,
T_NAMESPACE,
T_STRING, // Compat for PHPCS < 2.4.0 and PHP < 5.3.
);
return $targets;
}
/**
* 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(File $phpcsFile, $stackPtr)
{
if ($this->supportsAbove('7.0') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
$tokenCode = $tokens[$stackPtr]['code'];
$tokenType = $tokens[$stackPtr]['type'];
$tokenContentLc = strtolower($tokens[$stackPtr]['content']);
// For string tokens we only care about 'trait' as that is the only one
// which may not be correctly recognized as it's own token.
// This only happens in older versions of PHP where the token doesn't exist yet as a keyword.
if ($tokenCode === T_STRING && $tokenContentLc !== 'trait') {
return;
}
if (in_array($tokenType, array('T_CLASS', 'T_INTERFACE', 'T_TRAIT'), true)) {
// Check for the declared name being a name which is not tokenized as T_STRING.
$nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
if ($nextNonEmpty !== false && isset($this->forbiddenTokens[$tokens[$nextNonEmpty]['code']]) === true) {
$name = $tokens[$nextNonEmpty]['content'];
} else {
// Get the declared name if it's a T_STRING.
$name = $phpcsFile->getDeclarationName($stackPtr);
}
unset($nextNonEmpty);
if (isset($name) === false || is_string($name) === false || $name === '') {
return;
}
$nameLc = strtolower($name);
if (isset($this->allForbiddenNames[$nameLc]) === false) {
return;
}
} elseif ($tokenCode === T_NAMESPACE) {
$namespaceName = $this->getDeclaredNamespaceName($phpcsFile, $stackPtr);
if ($namespaceName === false || $namespaceName === '') {
return;
}
$namespaceParts = explode('\\', $namespaceName);
foreach ($namespaceParts as $namespacePart) {
$partLc = strtolower($namespacePart);
if (isset($this->allForbiddenNames[$partLc]) === true) {
$name = $namespacePart;
$nameLc = $partLc;
break;
}
}
} elseif ($tokenCode === T_STRING) {
// Traits which are not yet tokenized as T_TRAIT.
$nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
if ($nextNonEmpty === false) {
return;
}
$nextNonEmptyCode = $tokens[$nextNonEmpty]['code'];
if ($nextNonEmptyCode !== T_STRING && isset($this->forbiddenTokens[$nextNonEmptyCode]) === true) {
$name = $tokens[$nextNonEmpty]['content'];
$nameLc = strtolower($tokens[$nextNonEmpty]['content']);
} elseif ($nextNonEmptyCode === T_STRING) {
$endOfStatement = $phpcsFile->findNext(array(T_SEMICOLON, T_OPEN_CURLY_BRACKET), ($stackPtr + 1));
if ($endOfStatement === false) {
return;
}
do {
$nextNonEmptyLc = strtolower($tokens[$nextNonEmpty]['content']);
if (isset($this->allForbiddenNames[$nextNonEmptyLc]) === true) {
$name = $tokens[$nextNonEmpty]['content'];
$nameLc = $nextNonEmptyLc;
break;
}
$nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($nextNonEmpty + 1), $endOfStatement, true);
} while ($nextNonEmpty !== false);
}
unset($nextNonEmptyCode, $nextNonEmptyLc, $endOfStatement);
}
if (isset($name, $nameLc) === false) {
return;
}
// Still here, so this is one of the reserved words.
// Build up the error message.
$error = "'%s' is a";
$isError = null;
$errorCode = $this->stringToErrorCode($nameLc) . 'Found';
$data = array(
$nameLc,
);
if (isset($this->softReservedNames[$nameLc]) === true
&& $this->supportsAbove($this->softReservedNames[$nameLc]) === true
) {
$error .= ' soft reserved keyword as of PHP version %s';
$isError = false;
$data[] = $this->softReservedNames[$nameLc];
}
if (isset($this->forbiddenNames[$nameLc]) === true
&& $this->supportsAbove($this->forbiddenNames[$nameLc]) === true
) {
if (isset($isError) === true) {
$error .= ' and a';
}
$error .= ' reserved keyword as of PHP version %s';
$isError = true;
$data[] = $this->forbiddenNames[$nameLc];
}
if (isset($isError) === true) {
$error .= ' and should not be used to name a class, interface or trait or as part of a namespace (%s)';
$data[] = $tokens[$stackPtr]['type'];
$this->addMessage($phpcsFile, $error, $stackPtr, $isError, $errorCode, $data);
}
}
}
@@ -0,0 +1,180 @@
<?php
/**
* \PHPCompatibility\Sniffs\Keywords\ForbiddenNamesAsInvokedFunctionsSniff.
*
* @category PHP
* @package PHPCompatibility
* @author Jansen Price <jansen.price@gmail.com>
* @copyright 2012 Cu.be Solutions bvba
*/
namespace PHPCompatibility\Sniffs\Keywords;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* \PHPCompatibility\Sniffs\Keywords\ForbiddenNamesAsInvokedFunctionsSniff.
*
* Prohibits the use of reserved keywords invoked as functions.
*
* @category PHP
* @package PHPCompatibility
* @author Jansen Price <jansen.price@gmail.com>
* @copyright 2012 Cu.be Solutions bvba
*/
class ForbiddenNamesAsInvokedFunctionsSniff extends Sniff
{
/**
* List of tokens to register.
*
* @var array
*/
protected $targetedTokens = array(
T_ABSTRACT => '5.0',
T_CALLABLE => '5.4',
T_CATCH => '5.0',
T_FINAL => '5.0',
T_FINALLY => '5.5',
T_GOTO => '5.3',
T_IMPLEMENTS => '5.0',
T_INTERFACE => '5.0',
T_INSTANCEOF => '5.0',
T_INSTEADOF => '5.4',
T_NAMESPACE => '5.3',
T_PRIVATE => '5.0',
T_PROTECTED => '5.0',
T_PUBLIC => '5.0',
T_TRAIT => '5.4',
T_TRY => '5.0',
);
/**
* T_STRING keywords to recognize as targetted tokens.
*
* Compatibility for PHP versions where the keyword is not yet recognized
* as its own token and for PHPCS versions which change the token to
* T_STRING when used in a method call.
*
* @var array
*/
protected $targetedStringTokens = array(
'abstract' => '5.0',
'callable' => '5.4',
'catch' => '5.0',
'final' => '5.0',
'finally' => '5.5',
'goto' => '5.3',
'implements' => '5.0',
'interface' => '5.0',
'instanceof' => '5.0',
'insteadof' => '5.4',
'namespace' => '5.3',
'private' => '5.0',
'protected' => '5.0',
'public' => '5.0',
'trait' => '5.4',
'try' => '5.0',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
$tokens = array_keys($this->targetedTokens);
$tokens[] = T_STRING;
return $tokens;
}
/**
* 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(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$tokenCode = $tokens[$stackPtr]['code'];
$tokenContentLc = strtolower($tokens[$stackPtr]['content']);
$isString = false;
/*
* For string tokens we only care if the string is a reserved word used
* as a function. This only happens in older versions of PHP where the
* token doesn't exist yet for that keyword or in later versions when the
* token is used in a method invocation.
*/
if ($tokenCode === T_STRING
&& (isset($this->targetedStringTokens[$tokenContentLc]) === false)
) {
return;
}
if ($tokenCode === T_STRING) {
$isString = true;
}
// Make sure this is a function call.
$next = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
if ($next === false || $tokens[$next]['code'] !== T_OPEN_PARENTHESIS) {
// Not a function call.
return;
}
// This sniff isn't concerned about function declarations.
$prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true);
if ($prev !== false && $tokens[$prev]['code'] === T_FUNCTION) {
return;
}
/*
* Deal with PHP 7 relaxing the rules.
* "As of PHP 7.0.0 these keywords are allowed as property, constant, and method names
* of classes, interfaces and traits...", i.e. they can be invoked as a method call.
*
* Only needed for those keywords which we sniff out via T_STRING.
*/
if (($tokens[$prev]['code'] === T_OBJECT_OPERATOR || $tokens[$prev]['code'] === T_DOUBLE_COLON)
&& $this->supportsBelow('5.6') === false
) {
return;
}
// For the word catch, it is valid to have an open parenthesis
// after it, but only if it is preceded by a right curly brace.
if ($tokenCode === T_CATCH) {
if ($prev !== false && $tokens[$prev]['code'] === T_CLOSE_CURLY_BRACKET) {
// Ok, it's fine.
return;
}
}
if ($isString === true) {
$version = $this->targetedStringTokens[$tokenContentLc];
} else {
$version = $this->targetedTokens[$tokenCode];
}
if ($this->supportsAbove($version)) {
$error = "'%s' is a reserved keyword introduced in PHP version %s and cannot be invoked as a function (%s)";
$errorCode = $this->stringToErrorCode($tokenContentLc) . 'Found';
$data = array(
$tokenContentLc,
$version,
$tokens[$stackPtr]['type'],
);
$phpcsFile->addError($error, $stackPtr, $errorCode, $data);
}
}
}
@@ -0,0 +1,391 @@
<?php
/**
* \PHPCompatibility\Sniffs\Keywords\ForbiddenNamesSniff.
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
* @copyright 2012 Cu.be Solutions bvba
*/
namespace PHPCompatibility\Sniffs\Keywords;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* \PHPCompatibility\Sniffs\Keywords\ForbiddenNamesSniff.
*
* Prohibits the use of reserved keywords as class, function, namespace or constant names.
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
* @copyright 2012 Cu.be Solutions bvba
*/
class ForbiddenNamesSniff extends Sniff
{
/**
* A list of keywords that can not be used as function, class and namespace name or constant name.
* Mentions since which version it's not allowed.
*
* @var array(string => string)
*/
protected $invalidNames = array(
'abstract' => '5.0',
'and' => 'all',
'array' => 'all',
'as' => 'all',
'break' => 'all',
'callable' => '5.4',
'case' => 'all',
'catch' => '5.0',
'class' => 'all',
'clone' => '5.0',
'const' => 'all',
'continue' => 'all',
'declare' => 'all',
'default' => 'all',
'do' => 'all',
'else' => 'all',
'elseif' => 'all',
'enddeclare' => 'all',
'endfor' => 'all',
'endforeach' => 'all',
'endif' => 'all',
'endswitch' => 'all',
'endwhile' => 'all',
'extends' => 'all',
'final' => '5.0',
'finally' => '5.5',
'for' => 'all',
'foreach' => 'all',
'function' => 'all',
'global' => 'all',
'goto' => '5.3',
'if' => 'all',
'implements' => '5.0',
'interface' => '5.0',
'instanceof' => '5.0',
'insteadof' => '5.4',
'namespace' => '5.3',
'new' => 'all',
'or' => 'all',
'private' => '5.0',
'protected' => '5.0',
'public' => '5.0',
'static' => 'all',
'switch' => 'all',
'throw' => '5.0',
'trait' => '5.4',
'try' => '5.0',
'use' => 'all',
'var' => 'all',
'while' => 'all',
'xor' => 'all',
'__class__' => 'all',
'__dir__' => '5.3',
'__file__' => 'all',
'__function__' => 'all',
'__method__' => 'all',
'__namespace__' => '5.3',
);
/**
* A list of keywords that can follow use statements.
*
* @var array(string => string)
*/
protected $validUseNames = array(
'const' => true,
'function' => true,
);
/**
* Scope modifiers and other keywords allowed in trait use statements.
*
* @var array
*/
private $allowedModifiers = array();
/**
* Targeted tokens.
*
* @var array
*/
protected $targetedTokens = array(
T_CLASS,
T_FUNCTION,
T_NAMESPACE,
T_STRING,
T_CONST,
T_USE,
T_AS,
T_EXTENDS,
T_INTERFACE,
T_TRAIT,
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
$this->allowedModifiers = Tokens::$scopeModifiers;
$this->allowedModifiers[T_FINAL] = T_FINAL;
$tokens = $this->targetedTokens;
if (defined('T_ANON_CLASS')) {
$tokens[] = T_ANON_CLASS;
}
return $tokens;
}
/**
* 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(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
/*
* We distinguish between the class, function and namespace names vs the define statements.
*/
if ($tokens[$stackPtr]['type'] === 'T_STRING') {
$this->processString($phpcsFile, $stackPtr, $tokens);
} else {
$this->processNonString($phpcsFile, $stackPtr, $tokens);
}
}
/**
* 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.
* @param array $tokens The stack of tokens that make up
* the file.
*
* @return void
*/
public function processNonString(File $phpcsFile, $stackPtr, $tokens)
{
$nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true);
if ($nextNonEmpty === false) {
return;
}
/*
* Deal with anonymous classes - `class` before a reserved keyword is sometimes
* misidentified as `T_ANON_CLASS`.
* In PHPCS < 2.3.4 these were tokenized as T_CLASS no matter what.
*/
if ($tokens[$stackPtr]['type'] === 'T_ANON_CLASS' || $tokens[$stackPtr]['type'] === 'T_CLASS') {
$prevNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true);
if ($prevNonEmpty !== false && $tokens[$prevNonEmpty]['type'] === 'T_NEW') {
return;
}
}
/*
* PHP 5.6 allows for use const and use function, but only if followed by the function/constant name.
* - `use function HelloWorld` => move to the next token (HelloWorld) to verify.
* - `use const HelloWorld` => move to the next token (HelloWorld) to verify.
*/
elseif ($tokens[$stackPtr]['type'] === 'T_USE'
&& isset($this->validUseNames[strtolower($tokens[$nextNonEmpty]['content'])]) === true
) {
$maybeUseNext = $phpcsFile->findNext(Tokens::$emptyTokens, ($nextNonEmpty + 1), null, true, null, true);
if ($maybeUseNext !== false && $this->isEndOfUseStatement($tokens[$maybeUseNext]) === false) {
$nextNonEmpty = $maybeUseNext;
}
}
/*
* Deal with visibility modifiers.
* - `use HelloWorld { sayHello as protected; }` => valid, bow out.
* - `use HelloWorld { sayHello as private myPrivateHello; }` => move to the next token to verify.
*/
elseif ($tokens[$stackPtr]['type'] === 'T_AS'
&& isset($this->allowedModifiers[$tokens[$nextNonEmpty]['code']]) === true
&& $phpcsFile->hasCondition($stackPtr, T_USE) === true
) {
$maybeUseNext = $phpcsFile->findNext(Tokens::$emptyTokens, ($nextNonEmpty + 1), null, true, null, true);
if ($maybeUseNext === false || $this->isEndOfUseStatement($tokens[$maybeUseNext]) === true) {
return;
}
$nextNonEmpty = $maybeUseNext;
}
/*
* Deal with functions declared to return by reference.
*/
elseif ($tokens[$stackPtr]['type'] === 'T_FUNCTION'
&& $tokens[$nextNonEmpty]['type'] === 'T_BITWISE_AND'
) {
$maybeUseNext = $phpcsFile->findNext(Tokens::$emptyTokens, ($nextNonEmpty + 1), null, true, null, true);
if ($maybeUseNext === false) {
// Live coding.
return;
}
$nextNonEmpty = $maybeUseNext;
}
/*
* Deal with nested namespaces.
*/
elseif ($tokens[$stackPtr]['type'] === 'T_NAMESPACE') {
if ($tokens[$stackPtr + 1]['code'] === T_NS_SEPARATOR) {
// Not a namespace declaration, but use of, i.e. namespace\someFunction();
return;
}
$endToken = $phpcsFile->findNext(array(T_SEMICOLON, T_OPEN_CURLY_BRACKET), ($stackPtr + 1), null, false, null, true);
$namespaceName = trim($phpcsFile->getTokensAsString(($stackPtr + 1), ($endToken - $stackPtr - 1)));
if (empty($namespaceName) === true) {
return;
}
$namespaceParts = explode('\\', $namespaceName);
foreach ($namespaceParts as $namespacePart) {
$partLc = strtolower($namespacePart);
if (isset($this->invalidNames[$partLc]) === false) {
continue;
}
// Find the token position of the part which matched.
for ($i = ($stackPtr + 1); $i < $endToken; $i++) {
if ($tokens[$i]['content'] === $namespacePart) {
$nextNonEmpty = $i;
break;
}
}
}
unset($i, $namespacePart, $partLc);
}
$nextContentLc = strtolower($tokens[$nextNonEmpty]['content']);
if (isset($this->invalidNames[$nextContentLc]) === false) {
return;
}
/*
* Deal with PHP 7 relaxing the rules.
* "As of PHP 7.0.0 these keywords are allowed as property, constant, and method names
* of classes, interfaces and traits, except that class may not be used as constant name."
*/
if ((($tokens[$stackPtr]['type'] === 'T_FUNCTION'
&& $this->inClassScope($phpcsFile, $stackPtr, false) === true)
|| ($tokens[$stackPtr]['type'] === 'T_CONST'
&& $this->isClassConstant($phpcsFile, $stackPtr) === true
&& $nextContentLc !== 'class'))
&& $this->supportsBelow('5.6') === false
) {
return;
}
if ($this->supportsAbove($this->invalidNames[$nextContentLc])) {
$data = array(
$tokens[$nextNonEmpty]['content'],
$this->invalidNames[$nextContentLc],
);
$this->addError($phpcsFile, $stackPtr, $tokens[$nextNonEmpty]['content'], $data);
}
}
/**
* 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.
* @param array $tokens The stack of tokens that make up
* the file.
*
* @return void
*/
public function processString(File $phpcsFile, $stackPtr, $tokens)
{
$tokenContentLc = strtolower($tokens[$stackPtr]['content']);
/*
* Special case for PHP versions where the target is not yet identified as
* its own token, but presents as T_STRING.
* - trait keyword in PHP < 5.4
*/
if (version_compare(PHP_VERSION_ID, '50400', '<') && $tokenContentLc === 'trait') {
$this->processNonString($phpcsFile, $stackPtr, $tokens);
return;
}
// Look for any define/defined tokens (both T_STRING ones, blame Tokenizer).
if ($tokenContentLc !== 'define' && $tokenContentLc !== 'defined') {
return;
}
// Retrieve the define(d) constant name.
$firstParam = $this->getFunctionCallParameter($phpcsFile, $stackPtr, 1);
if ($firstParam === false) {
return;
}
$defineName = $this->stripQuotes($firstParam['raw']);
$defineNameLc = strtolower($defineName);
if (isset($this->invalidNames[$defineNameLc]) && $this->supportsAbove($this->invalidNames[$defineNameLc])) {
$data = array(
$defineName,
$this->invalidNames[$defineNameLc],
);
$this->addError($phpcsFile, $stackPtr, $defineNameLc, $data);
}
}
/**
* Add the error message.
*
* @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token in the
* stack passed in $tokens.
* @param string $content The token content found.
* @param array $data The data to pass into the error message.
*
* @return void
*/
protected function addError(File $phpcsFile, $stackPtr, $content, $data)
{
$error = "Function name, class name, namespace name or constant name can not be reserved keyword '%s' (since version %s)";
$errorCode = $this->stringToErrorCode($content) . 'Found';
$phpcsFile->addError($error, $stackPtr, $errorCode, $data);
}
/**
* Check if the current token code is for a token which can be considered
* the end of a (partial) use statement.
*
* @param int $token The current token information.
*
* @return bool
*/
protected function isEndOfUseStatement($token)
{
return in_array($token['code'], array(T_CLOSE_CURLY_BRACKET, T_SEMICOLON, T_COMMA), true);
}
}
@@ -0,0 +1,366 @@
<?php
/**
* \PHPCompatibility\Sniffs\Keywords\NewKeywordsSniff.
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
* @copyright 2013 Cu.be Solutions bvba
*/
namespace PHPCompatibility\Sniffs\Keywords;
use PHPCompatibility\AbstractNewFeatureSniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* \PHPCompatibility\Sniffs\Keywords\NewKeywordsSniff.
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
* @copyright 2013 Cu.be Solutions bvba
*/
class NewKeywordsSniff extends AbstractNewFeatureSniff
{
/**
* A list of new keywords, not present in older versions.
*
* The array lists : version number with false (not present) or true (present).
* If's sufficient to list the last version which did not contain the keyword.
*
* Description will be used as part of the error message.
* Condition is the name of a callback method within this class or the parent class
* which checks whether the token complies with a certain condition.
* The callback function will be passed the $phpcsFile and the $stackPtr.
* The callback function should return `true` if the condition is met and the
* error should *not* be thrown.
*
* @var array(string => array(string => int|string|null))
*/
protected $newKeywords = array(
'T_HALT_COMPILER' => array(
'5.0' => false,
'5.1' => true,
'description' => '"__halt_compiler" keyword',
),
'T_CONST' => array(
'5.2' => false,
'5.3' => true,
'description' => '"const" keyword',
'condition' => 'isClassConstant', // Keyword is only new when not in class context.
),
'T_CALLABLE' => array(
'5.3' => false,
'5.4' => true,
'description' => '"callable" keyword',
'content' => 'callable',
),
'T_DIR' => array(
'5.2' => false,
'5.3' => true,
'description' => '__DIR__ magic constant',
'content' => '__DIR__',
),
'T_GOTO' => array(
'5.2' => false,
'5.3' => true,
'description' => '"goto" keyword',
'content' => 'goto',
),
'T_INSTEADOF' => array(
'5.3' => false,
'5.4' => true,
'description' => '"insteadof" keyword (for traits)',
'content' => 'insteadof',
),
'T_NAMESPACE' => array(
'5.2' => false,
'5.3' => true,
'description' => '"namespace" keyword',
'content' => 'namespace',
),
'T_NS_C' => array(
'5.2' => false,
'5.3' => true,
'description' => '__NAMESPACE__ magic constant',
'content' => '__NAMESPACE__',
),
'T_USE' => array(
'5.2' => false,
'5.3' => true,
'description' => '"use" keyword (for traits/namespaces/anonymous functions)',
),
'T_START_NOWDOC' => array(
'5.2' => false,
'5.3' => true,
'description' => 'nowdoc functionality',
),
'T_END_NOWDOC' => array(
'5.2' => false,
'5.3' => true,
'description' => 'nowdoc functionality',
),
'T_START_HEREDOC' => array(
'5.2' => false,
'5.3' => true,
'description' => '(Double) quoted Heredoc identifier',
'condition' => 'isNotQuoted', // Heredoc is only new with quoted identifier.
),
'T_TRAIT' => array(
'5.3' => false,
'5.4' => true,
'description' => '"trait" keyword',
'content' => 'trait',
),
'T_TRAIT_C' => array(
'5.3' => false,
'5.4' => true,
'description' => '__TRAIT__ magic constant',
'content' => '__TRAIT__',
),
// The specifics for distinguishing between 'yield' and 'yield from' are dealt
// with in the translation logic.
// This token has to be placed above the `T_YIELD` token in this array to allow for this.
'T_YIELD_FROM' => array(
'5.6' => false,
'7.0' => true,
'description' => '"yield from" keyword (for generators)',
'content' => 'yield',
),
'T_YIELD' => array(
'5.4' => false,
'5.5' => true,
'description' => '"yield" keyword (for generators)',
'content' => 'yield',
),
'T_FINALLY' => array(
'5.4' => false,
'5.5' => true,
'description' => '"finally" keyword (in exception handling)',
'content' => 'finally',
),
);
/**
* Translation table for T_STRING tokens.
*
* Will be set up from the register() method.
*
* @var array(string => string)
*/
protected $translateContentToToken = array();
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
$tokens = array();
$translate = array();
foreach ($this->newKeywords as $token => $versions) {
if (defined($token)) {
$tokens[] = constant($token);
}
if (isset($versions['content'])) {
$translate[strtolower($versions['content'])] = $token;
}
}
/*
* Deal with tokens not recognized by the PHP version the sniffer is run
* under and (not correctly) compensated for by PHPCS.
*/
if (empty($translate) === false) {
$this->translateContentToToken = $translate;
$tokens[] = T_STRING;
}
return $tokens;
}
/**
* 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(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$tokenType = $tokens[$stackPtr]['type'];
// Allow for dealing with multi-token keywords, like "yield from".
$end = $stackPtr;
// Translate T_STRING token if necessary.
if ($tokens[$stackPtr]['type'] === 'T_STRING') {
$content = strtolower($tokens[$stackPtr]['content']);
if (isset($this->translateContentToToken[$content]) === false) {
// Not one of the tokens we're looking for.
return;
}
$tokenType = $this->translateContentToToken[$content];
}
/*
* Special case: distinguish between `yield` and `yield from`.
*
* PHPCS currently (at least up to v 3.0.1) does not backfill for the
* `yield` nor the `yield from` keywords.
* See: https://github.com/squizlabs/PHP_CodeSniffer/issues/1524
*
* In PHP < 5.5, both `yield` as well as `from` are tokenized as T_STRING.
* In PHP 5.5 - 5.6, `yield` is tokenized as T_YIELD and `from` as T_STRING,
* but the `T_YIELD_FROM` token *is* defined in PHP.
* In PHP 7.0+ both are tokenized as their respective token, however,
* a multi-line "yield from" is tokenized as two tokens.
*/
if ($tokenType === 'T_YIELD') {
$nextToken = $phpcsFile->findNext(T_WHITESPACE, ($end + 1), null, true);
if ($tokens[$nextToken]['code'] === T_STRING
&& $tokens[$nextToken]['content'] === 'from'
) {
$tokenType = 'T_YIELD_FROM';
$end = $nextToken;
}
unset($nextToken);
}
if ($tokenType === 'T_YIELD_FROM' && $tokens[($stackPtr - 1)]['type'] === 'T_YIELD_FROM') {
// Multi-line "yield from", no need to report it twice.
return;
}
if (isset($this->newKeywords[$tokenType]) === false) {
return;
}
$nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, ($end + 1), null, true);
$prevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true);
if ($prevToken !== false
&& ($tokens[$prevToken]['code'] === T_DOUBLE_COLON
|| $tokens[$prevToken]['code'] === T_OBJECT_OPERATOR)
) {
// Class property of the same name as one of the keywords. Ignore.
return;
}
// Skip attempts to use keywords as functions or class names - the former
// will be reported by ForbiddenNamesAsInvokedFunctionsSniff, whilst the
// latter will be (partially) reported by the ForbiddenNames sniff.
// Either type will result in false-positives when targetting lower versions
// of PHP where the name was not reserved, unless we explicitly check for
// them.
if (($nextToken === false
|| $tokens[$nextToken]['type'] !== 'T_OPEN_PARENTHESIS')
&& ($prevToken === false
|| $tokens[$prevToken]['type'] !== 'T_CLASS'
|| $tokens[$prevToken]['type'] !== 'T_INTERFACE')
) {
// Skip based on token scope condition.
if (isset($this->newKeywords[$tokenType]['condition'])
&& call_user_func(array($this, $this->newKeywords[$tokenType]['condition']), $phpcsFile, $stackPtr) === true
) {
return;
}
$itemInfo = array(
'name' => $tokenType,
);
$this->handleFeature($phpcsFile, $stackPtr, $itemInfo);
}
}
/**
* Get the relevant sub-array for a specific item from a multi-dimensional array.
*
* @param array $itemInfo Base information about the item.
*
* @return array Version and other information about the item.
*/
public function getItemArray(array $itemInfo)
{
return $this->newKeywords[$itemInfo['name']];
}
/**
* Get an array of the non-PHP-version array keys used in a sub-array.
*
* @return array
*/
protected function getNonVersionArrayKeys()
{
return array(
'description',
'condition',
'content',
);
}
/**
* Retrieve the relevant detail (version) information for use in an error message.
*
* @param array $itemArray Version and other information about the item.
* @param array $itemInfo Base information about the item.
*
* @return array
*/
public function getErrorInfo(array $itemArray, array $itemInfo)
{
$errorInfo = parent::getErrorInfo($itemArray, $itemInfo);
$errorInfo['description'] = $itemArray['description'];
return $errorInfo;
}
/**
* Allow for concrete child classes to filter the error data before it's passed to PHPCS.
*
* @param array $data The error data array which was created.
* @param array $itemInfo Base information about the item this error message applies to.
* @param array $errorInfo Detail information about an item this error message applies to.
*
* @return array
*/
protected function filterErrorData(array $data, array $itemInfo, array $errorInfo)
{
$data[0] = $errorInfo['description'];
return $data;
}
/**
* Callback for the quoted heredoc identifier condition.
*
* A double quoted identifier will have the opening quote on position 3
* in the string: `<<<"ID"`.
*
* @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 bool
*/
public function isNotQuoted(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
return ($tokens[$stackPtr]['content'][3] !== '"');
}
}