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,79 @@
<?php
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\ForbiddenParameterShadowSuperGlobalsSniff
*
* PHP version 5.4
*
* @category PHP
* @package PHPCompatibility
* @author Declan Kelly <declankelly90@gmail.com>
* @copyright 2015 Declan Kelly
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\ForbiddenParameterShadowSuperGlobalsSniff
*
* Discourages use of superglobals as parameters for functions.
*
* {@internal List of superglobals is maintained in the parent class.}}
*
* PHP version 5.4
*
* @category PHP
* @package PHPCompatibility
* @author Declan Kelly <declankelly90@gmail.com>
* @copyright 2015 Declan Kelly
*/
class ForbiddenParameterShadowSuperGlobalsSniff extends Sniff
{
/**
* Register the tokens to listen for.
*
* @return array
*/
public function register()
{
return array(
T_FUNCTION,
T_CLOSURE,
);
}
/**
* Processes the test.
*
* @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the current token.
*
* @return void
*/
public function process(File $phpcsFile, $stackPtr)
{
if ($this->supportsAbove('5.4') === false) {
return;
}
// Get all parameters from function signature.
$parameters = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr);
if (empty($parameters) || is_array($parameters) === false) {
return;
}
foreach ($parameters as $param) {
if (isset($this->superglobals[$param['name']]) === true) {
$error = 'Parameter shadowing super global (%s) causes fatal error since PHP 5.4';
$errorCode = $this->stringToErrorCode(substr($param['name'], 1)) . 'Found';
$data = array($param['name']);
$phpcsFile->addError($error, $param['token'], $errorCode, $data);
}
}
}
}
@@ -0,0 +1,86 @@
<?php
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\ForbiddenParametersWithSameName.
*
* PHP version 7.0
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim@cu.be>
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\ForbiddenParametersWithSameName.
*
* Functions can not have multiple parameters with the same name since PHP 7.0
*
* PHP version 7.0
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim@cu.be>
*/
class ForbiddenParametersWithSameNameSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_FUNCTION,
T_CLOSURE,
);
}
/**
* 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();
$token = $tokens[$stackPtr];
// Skip function without body.
if (isset($token['scope_opener']) === false) {
return;
}
// Get all parameters from method signature.
$parameters = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr);
if (empty($parameters) || is_array($parameters) === false) {
return;
}
$paramNames = array();
foreach ($parameters as $param) {
$paramNames[] = strtolower($param['name']);
}
if (count($paramNames) !== count(array_unique($paramNames))) {
$phpcsFile->addError(
'Functions can not have multiple parameters with the same name since PHP 7.0',
$stackPtr,
'Found'
);
}
}
}
@@ -0,0 +1,118 @@
<?php
/**
* PHP 7.1 Forbidden variable names in closure use statements.
*
* PHP version 7.1
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* PHP 7.1 Forbidden variable names in closure use statements.
*
* Variables bound to a closure via the use construct cannot use the same name
* as any superglobals, $this, or any parameter since PHP 7.1.
*
* PHP version 7.1
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
class ForbiddenVariableNamesInClosureUseSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_USE);
}
/**
* 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.1') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
// Verify this use statement is used with a closure - if so, it has to have parenthesis before it.
$previousNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true, null, true);
if ($previousNonEmpty === false || $tokens[$previousNonEmpty]['code'] !== T_CLOSE_PARENTHESIS
|| isset($tokens[$previousNonEmpty]['parenthesis_opener']) === false
) {
return;
}
// ... and (a variable within) parenthesis after it.
$nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
if ($nextNonEmpty === false || $tokens[$nextNonEmpty]['code'] !== T_OPEN_PARENTHESIS) {
return;
}
if (isset($tokens[$nextNonEmpty]['parenthesis_closer']) === false) {
// Live coding.
return;
}
$closurePtr = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($tokens[$previousNonEmpty]['parenthesis_opener'] - 1), null, true);
if ($closurePtr === false || $tokens[$closurePtr]['code'] !== T_CLOSURE) {
return;
}
// Get the parameters declared by the closure.
$closureParams = PHPCSHelper::getMethodParameters($phpcsFile, $closurePtr);
$errorMsg = 'Variables bound to a closure via the use construct cannot use the same name as superglobals, $this, or a declared parameter since PHP 7.1. Found: %s';
for ($i = ($nextNonEmpty + 1); $i < $tokens[$nextNonEmpty]['parenthesis_closer']; $i++) {
if ($tokens[$i]['code'] !== T_VARIABLE) {
continue;
}
$variableName = $tokens[$i]['content'];
if ($variableName === '$this') {
$phpcsFile->addError($errorMsg, $i, 'FoundThis', array($variableName));
continue;
}
if (isset($this->superglobals[$variableName]) === true) {
$phpcsFile->addError($errorMsg, $i, 'FoundSuperglobal', array($variableName));
continue;
}
// Check whether it is one of the parameters declared by the closure.
if (empty($closureParams) === false) {
foreach ($closureParams as $param) {
if ($param['name'] === $variableName) {
$phpcsFile->addError($errorMsg, $i, 'FoundShadowParam', array($variableName));
continue 2;
}
}
}
}
}
}
@@ -0,0 +1,237 @@
<?php
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NewClosure.
*
* PHP version 5.3
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim@cu.be>
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NewClosure.
*
* Closures are available since PHP 5.3
*
* PHP version 5.3
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim@cu.be>
*/
class NewClosureSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(T_CLOSURE);
}
/**
* 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.2')) {
$phpcsFile->addError(
'Closures / anonymous functions are not available in PHP 5.2 or earlier',
$stackPtr,
'Found'
);
}
/*
* Closures can only be declared as static since PHP 5.4.
*/
$isStatic = $this->isClosureStatic($phpcsFile, $stackPtr);
if ($this->supportsBelow('5.3') && $isStatic === true) {
$phpcsFile->addError(
'Closures / anonymous functions could not be declared as static in PHP 5.3 or earlier',
$stackPtr,
'StaticFound'
);
}
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['scope_opener'], $tokens[$stackPtr]['scope_closer']) === false) {
// Live coding or parse error.
return;
}
$scopeStart = ($tokens[$stackPtr]['scope_opener'] + 1);
$scopeEnd = $tokens[$stackPtr]['scope_closer'];
$usesThis = $this->findThisUsageInClosure($phpcsFile, $scopeStart, $scopeEnd);
if ($this->supportsBelow('5.3')) {
/*
* Closures declared within classes only have access to $this since PHP 5.4.
*/
if ($usesThis !== false) {
$thisFound = $usesThis;
do {
$phpcsFile->addError(
'Closures / anonymous functions did not have access to $this in PHP 5.3 or earlier',
$thisFound,
'ThisFound'
);
$thisFound = $this->findThisUsageInClosure($phpcsFile, ($thisFound + 1), $scopeEnd);
} while ($thisFound !== false);
}
/*
* Closures declared within classes only have access to self/parent/static since PHP 5.4.
*/
$usesClassRef = $this->findClassRefUsageInClosure($phpcsFile, $scopeStart, $scopeEnd);
if ($usesClassRef !== false) {
do {
$phpcsFile->addError(
'Closures / anonymous functions could not use "%s::" in PHP 5.3 or earlier',
$usesClassRef,
'ClassRefFound',
array(strtolower($tokens[$usesClassRef]['content']))
);
$usesClassRef = $this->findClassRefUsageInClosure($phpcsFile, ($usesClassRef + 1), $scopeEnd);
} while ($usesClassRef !== false);
}
}
/*
* Check for correct usage.
*/
if ($this->supportsAbove('5.4') && $usesThis !== false) {
$thisFound = $usesThis;
do {
/*
* Closures only have access to $this if not declared as static.
*/
if ($isStatic === true) {
$phpcsFile->addError(
'Closures / anonymous functions declared as static do not have access to $this',
$thisFound,
'ThisFoundInStatic'
);
}
/*
* Closures only have access to $this if used within a class context.
*/
elseif ($this->inClassScope($phpcsFile, $stackPtr, false) === false) {
$phpcsFile->addWarning(
'Closures / anonymous functions only have access to $this if used within a class or when bound to an object using bindTo(). Please verify.',
$thisFound,
'ThisFoundOutsideClass'
);
}
$thisFound = $this->findThisUsageInClosure($phpcsFile, ($thisFound + 1), $scopeEnd);
} while ($thisFound !== false);
}
// Prevent double reporting for nested closures.
return $scopeEnd;
}
/**
* Check whether the closure is declared as static.
*
* @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
*/
protected function isClosureStatic(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$prevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true, null, true);
return ($prevToken !== false && $tokens[$prevToken]['code'] === T_STATIC);
}
/**
* Check if the code within a closure uses the $this variable.
*
* @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $startToken The position within the closure to continue searching from.
* @param int $endToken The closure scope closer to stop searching at.
*
* @return int|false The stackPtr to the first $this usage if found or false if
* $this is not used.
*/
protected function findThisUsageInClosure(File $phpcsFile, $startToken, $endToken)
{
// Make sure the $startToken is valid.
if ($startToken >= $endToken) {
return false;
}
return $phpcsFile->findNext(
T_VARIABLE,
$startToken,
$endToken,
false,
'$this'
);
}
/**
* Check if the code within a closure uses "self/parent/static".
*
* @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $startToken The position within the closure to continue searching from.
* @param int $endToken The closure scope closer to stop searching at.
*
* @return int|false The stackPtr to the first classRef usage if found or false if
* they are not used.
*/
protected function findClassRefUsageInClosure(File $phpcsFile, $startToken, $endToken)
{
// Make sure the $startToken is valid.
if ($startToken >= $endToken) {
return false;
}
$tokens = $phpcsFile->getTokens();
$classRef = $phpcsFile->findNext(array(T_SELF, T_PARENT, T_STATIC), $startToken, $endToken);
if ($classRef === false || $tokens[$classRef]['code'] !== T_STATIC) {
return $classRef;
}
// T_STATIC, make sure it is used as a class reference.
$next = $phpcsFile->findNext(Tokens::$emptyTokens, ($classRef + 1), $endToken, true);
if ($next === false || $tokens[$next]['code'] !== T_DOUBLE_COLON) {
return false;
}
return $classRef;
}
}
@@ -0,0 +1,162 @@
<?php
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NewNullableTypes.
*
* PHP version 7.1
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NewNullableTypes.
*
* Nullable type hints and return types are available since PHP 7.1.
*
* PHP version 7.1
*
* @category PHP
* @package PHPCompatibility
* @author Juliette Reinders Folmer <phpcompatibility_nospam@adviesenzo.nl>
*/
class NewNullableTypesSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* {@internal Not sniffing for T_NULLABLE which was introduced in PHPCS 2.7.2
* as in that case we can't distinguish between parameter type hints and
* return type hints for the error message.}}
*
* @return array
*/
public function register()
{
$tokens = array(
T_FUNCTION,
T_CLOSURE,
);
if (defined('T_RETURN_TYPE')) {
$tokens[] = T_RETURN_TYPE;
}
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)
{
if ($this->supportsBelow('7.0') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
$tokenCode = $tokens[$stackPtr]['code'];
if ($tokenCode === T_FUNCTION || $tokenCode === T_CLOSURE) {
$this->processFunctionDeclaration($phpcsFile, $stackPtr);
// Deal with older PHPCS version which don't recognize return type hints
// as well as newer PHPCS versions (3.3.0+) where the tokenization has changed.
$returnTypeHint = $this->getReturnTypeHintToken($phpcsFile, $stackPtr);
if ($returnTypeHint !== false) {
$this->processReturnType($phpcsFile, $returnTypeHint);
}
} else {
$this->processReturnType($phpcsFile, $stackPtr);
}
}
/**
* Process this test for function tokens.
*
* @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
*/
protected function processFunctionDeclaration(File $phpcsFile, $stackPtr)
{
$params = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr);
if (empty($params) === false && is_array($params)) {
foreach ($params as $param) {
if ($param['nullable_type'] === true) {
$phpcsFile->addError(
'Nullable type declarations are not supported in PHP 7.0 or earlier. Found: %s',
$param['token'],
'typeDeclarationFound',
array($param['type_hint'])
);
}
}
}
}
/**
* Process this test for return type tokens.
*
* @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
*/
protected function processReturnType(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if (isset($tokens[($stackPtr - 1)]['code']) === false) {
return;
}
$previous = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true);
// Deal with namespaced class names.
if ($tokens[$previous]['code'] === T_NS_SEPARATOR) {
$validTokens = Tokens::$emptyTokens;
$validTokens[T_STRING] = true;
$validTokens[T_NS_SEPARATOR] = true;
$stackPtr--;
while (isset($validTokens[$tokens[($stackPtr - 1)]['code']]) === true) {
$stackPtr--;
}
$previous = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true);
}
// T_NULLABLE token was introduced in PHPCS 2.7.2. Before that it identified as T_INLINE_THEN.
if ((defined('T_NULLABLE') === true && $tokens[$previous]['type'] === 'T_NULLABLE')
|| (defined('T_NULLABLE') === false && $tokens[$previous]['code'] === T_INLINE_THEN)
) {
$phpcsFile->addError(
'Nullable return types are not supported in PHP 7.0 or earlier.',
$stackPtr,
'returnTypeFound'
);
}
}
}
@@ -0,0 +1,195 @@
<?php
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NewParamTypeDeclarationsSniff.
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\AbstractNewFeatureSniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NewParamTypeDeclarationsSniff.
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
*/
class NewParamTypeDeclarationsSniff extends AbstractNewFeatureSniff
{
/**
* A list of new types.
*
* The array lists : version number with false (not present) or true (present).
* If's sufficient to list the first version where the keyword appears.
*
* @var array(string => array(string => int|string|null))
*/
protected $newTypes = array(
'array' => array(
'5.0' => false,
'5.1' => true,
),
'self' => array(
'5.1' => false,
'5.2' => true,
),
'parent' => array(
'5.1' => false,
'5.2' => true,
),
'callable' => array(
'5.3' => false,
'5.4' => true,
),
'int' => array(
'5.6' => false,
'7.0' => true,
),
'float' => array(
'5.6' => false,
'7.0' => true,
),
'bool' => array(
'5.6' => false,
'7.0' => true,
),
'string' => array(
'5.6' => false,
'7.0' => true,
),
'iterable' => array(
'7.0' => false,
'7.1' => true,
),
'object' => array(
'7.1' => false,
'7.2' => true,
),
);
/**
* Invalid types
*
* The array lists : the invalid type hint => what was probably intended/alternative.
*
* @var array(string => string)
*/
protected $invalidTypes = array(
'static' => 'self',
'boolean' => 'bool',
'integer' => 'int',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
return array(
T_FUNCTION,
T_CLOSURE,
);
}
/**
* 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)
{
// Get all parameters from method signature.
$paramNames = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr);
if (empty($paramNames)) {
return;
}
$supportsPHP4 = $this->supportsBelow('4.4');
foreach ($paramNames as $param) {
if ($param['type_hint'] === '') {
continue;
}
// Strip off potential nullable indication.
$typeHint = ltrim($param['type_hint'], '?');
if ($supportsPHP4 === true) {
$phpcsFile->addError(
'Type declarations were not present in PHP 4.4 or earlier.',
$param['token'],
'TypeHintFound'
);
} elseif (isset($this->newTypes[$typeHint])) {
$itemInfo = array(
'name' => $typeHint,
);
$this->handleFeature($phpcsFile, $param['token'], $itemInfo);
// As of PHP 7.0, using `self` or `parent` outside class scope throws a fatal error.
// Only throw this error for PHP 5.2+ as before that the "type hint not supported" error
// will be thrown.
if (($typeHint === 'self' || $typeHint === 'parent')
&& $this->inClassScope($phpcsFile, $stackPtr, false) === false
&& $this->supportsAbove('5.2') !== false
) {
$phpcsFile->addError(
"'%s' type cannot be used outside of class scope",
$param['token'],
ucfirst($typeHint) . 'OutsideClassScopeFound',
array($typeHint)
);
}
} elseif (isset($this->invalidTypes[$typeHint])) {
$error = "'%s' is not a valid type declaration. Did you mean %s ?";
$data = array(
$typeHint,
$this->invalidTypes[$typeHint],
);
$phpcsFile->addError($error, $param['token'], 'InvalidTypeHintFound', $data);
}
}
}
/**
* 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->newTypes[$itemInfo['name']];
}
/**
* Get the error message template for this sniff.
*
* @return string
*/
protected function getErrorMsgTemplate()
{
return "'%s' type declaration is not present in PHP version %s or earlier";
}
}
@@ -0,0 +1,173 @@
<?php
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NewReturnTypeDeclarationsSniff.
*
* PHP version 7.0
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\AbstractNewFeatureSniff;
use PHP_CodeSniffer_File as File;
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NewReturnTypeDeclarationsSniff.
*
* PHP version 7.0
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
*/
class NewReturnTypeDeclarationsSniff extends AbstractNewFeatureSniff
{
/**
* A list of new types
*
* The array lists : version number with false (not present) or true (present).
* If's sufficient to list the first version where the keyword appears.
*
* @var array(string => array(string => int|string|null))
*/
protected $newTypes = array(
'int' => array(
'5.6' => false,
'7.0' => true,
),
'float' => array(
'5.6' => false,
'7.0' => true,
),
'bool' => array(
'5.6' => false,
'7.0' => true,
),
'string' => array(
'5.6' => false,
'7.0' => true,
),
'array' => array(
'5.6' => false,
'7.0' => true,
),
'callable' => array(
'5.6' => false,
'7.0' => true,
),
'parent' => array(
'5.6' => false,
'7.0' => true,
),
'self' => array(
'5.6' => false,
'7.0' => true,
),
'Class name' => array(
'5.6' => false,
'7.0' => true,
),
'iterable' => array(
'7.0' => false,
'7.1' => true,
),
'void' => array(
'7.0' => false,
'7.1' => true,
),
'object' => array(
'7.1' => false,
'7.2' => true,
),
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
$tokens = array(
T_FUNCTION,
T_CLOSURE,
);
if (defined('T_RETURN_TYPE')) {
$tokens[] = T_RETURN_TYPE;
}
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();
// Deal with older PHPCS version which don't recognize return type hints
// as well as newer PHPCS versions (3.3.0+) where the tokenization has changed.
if ($tokens[$stackPtr]['code'] === T_FUNCTION || $tokens[$stackPtr]['code'] === T_CLOSURE) {
$returnTypeHint = $this->getReturnTypeHintToken($phpcsFile, $stackPtr);
if ($returnTypeHint !== false) {
$stackPtr = $returnTypeHint;
}
}
if (isset($this->newTypes[$tokens[$stackPtr]['content']]) === true) {
$itemInfo = array(
'name' => $tokens[$stackPtr]['content'],
);
$this->handleFeature($phpcsFile, $stackPtr, $itemInfo);
}
// Handle class name based return types.
elseif ($tokens[$stackPtr]['code'] === T_STRING
|| (defined('T_RETURN_TYPE') && $tokens[$stackPtr]['code'] === T_RETURN_TYPE)
) {
$itemInfo = array(
'name' => 'Class name',
);
$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->newTypes[$itemInfo['name']];
}
/**
* Get the error message template for this sniff.
*
* @return string
*/
protected function getErrorMsgTemplate()
{
return '%s return type is not present in PHP version %s or earlier';
}
}
@@ -0,0 +1,178 @@
<?php
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NonStaticMagicMethodsSniff.
*
* PHP version 5.4
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
* @copyright 2012 Cu.be Solutions bvba
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
/**
* \PHPCompatibility\Sniffs\FunctionDeclarations\NonStaticMagicMethodsSniff.
*
* Verifies the use of the correct visibility and static properties of magic methods.
*
* @category PHP
* @package PHPCompatibility
* @author Wim Godden <wim.godden@cu.be>
* @copyright 2012 Cu.be Solutions bvba
*/
class NonStaticMagicMethodsSniff extends Sniff
{
/**
* A list of PHP magic methods and their visibility and static requirements.
*
* Method names in the array should be all *lowercase*.
* Visibility can be either 'public', 'protected' or 'private'.
* Static can be either 'true' - *must* be static, or 'false' - *must* be non-static.
* When a method does not have a specific requirement for either visibility or static,
* do *not* add the key.
*
* @var array(string)
*/
protected $magicMethods = array(
'__get' => array(
'visibility' => 'public',
'static' => false,
),
'__set' => array(
'visibility' => 'public',
'static' => false,
),
'__isset' => array(
'visibility' => 'public',
'static' => false,
),
'__unset' => array(
'visibility' => 'public',
'static' => false,
),
'__call' => array(
'visibility' => 'public',
'static' => false,
),
'__callstatic' => array(
'visibility' => 'public',
'static' => true,
),
'__sleep' => array(
'visibility' => 'public',
),
'__tostring' => array(
'visibility' => 'public',
),
'__set_state' => array(
'static' => true,
),
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register()
{
$targets = array(
T_CLASS,
T_INTERFACE,
T_TRAIT,
);
if (defined('T_ANON_CLASS')) {
$targets[] = T_ANON_CLASS;
}
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)
{
// Should be removed, the requirement was previously also there, 5.3 just started throwing a warning about it.
if ($this->supportsAbove('5.3') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['scope_closer']) === false) {
return;
}
$classScopeCloser = $tokens[$stackPtr]['scope_closer'];
$functionPtr = $stackPtr;
// Find all the functions in this class or interface.
while (($functionToken = $phpcsFile->findNext(T_FUNCTION, $functionPtr, $classScopeCloser)) !== false) {
/*
* Get the scope closer for this function in order to know how
* to advance to the next function.
* If no body of function (e.g. for interfaces), there is
* no closing curly brace; advance the pointer differently.
*/
if (isset($tokens[$functionToken]['scope_closer'])) {
$scopeCloser = $tokens[$functionToken]['scope_closer'];
} else {
$scopeCloser = ($functionToken + 1);
}
$methodName = $phpcsFile->getDeclarationName($functionToken);
$methodNameLc = strtolower($methodName);
if (isset($this->magicMethods[$methodNameLc]) === false) {
$functionPtr = $scopeCloser;
continue;
}
$methodProperties = $phpcsFile->getMethodProperties($functionToken);
$errorCodeBase = $this->stringToErrorCode($methodNameLc);
if (isset($this->magicMethods[$methodNameLc]['visibility']) && $this->magicMethods[$methodNameLc]['visibility'] !== $methodProperties['scope']) {
$error = 'Visibility for magic method %s must be %s. Found: %s';
$errorCode = $errorCodeBase . 'MethodVisibility';
$data = array(
$methodName,
$this->magicMethods[$methodNameLc]['visibility'],
$methodProperties['scope'],
);
$phpcsFile->addError($error, $functionToken, $errorCode, $data);
}
if (isset($this->magicMethods[$methodNameLc]['static']) && $this->magicMethods[$methodNameLc]['static'] !== $methodProperties['is_static']) {
$error = 'Magic method %s cannot be defined as static.';
$errorCode = $errorCodeBase . 'MethodStatic';
$data = array($methodName);
if ($this->magicMethods[$methodNameLc]['static'] === true) {
$error = 'Magic method %s must be defined as static.';
$errorCode = $errorCodeBase . 'MethodNonStatic';
}
$phpcsFile->addError($error, $functionToken, $errorCode, $data);
}
// Advance to next function.
$functionPtr = $scopeCloser;
}
}
}