基础代码

This commit is contained in:
2021-02-26 22:23:13 +08:00
parent 7884df52f0
commit a719feebba
2585 changed files with 328263 additions and 0 deletions
@@ -0,0 +1,79 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
/**
* Detect the use of superglobals as parameters for functions, support for which was removed in PHP 5.4.
*
* {@internal List of superglobals is maintained in the parent class.}
*
* PHP version 5.4
*
* @link https://www.php.net/manual/en/migration54.incompatible.php
*
* @since 7.0.0
*/
class ForbiddenParameterShadowSuperGlobalsSniff extends Sniff
{
/**
* Register the tokens to listen for.
*
* @since 7.0.0
* @since 7.1.3 Allows for closures.
*
* @return array
*/
public function register()
{
return array(
\T_FUNCTION,
\T_CLOSURE,
);
}
/**
* Processes the test.
*
* @since 7.0.0
*
* @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,88 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
/**
* Functions can not have multiple parameters with the same name since PHP 7.0.
*
* PHP version 7.0
*
* @link https://www.php.net/manual/en/migration70.incompatible.php#migration70.incompatible.other.func-parameters
*
* @since 7.0.0
*/
class ForbiddenParametersWithSameNameSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 7.0.0
* @since 7.1.3 Allows for closures.
*
* @return array
*/
public function register()
{
return array(
\T_FUNCTION,
\T_CLOSURE,
);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 7.0.0
*
* @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[] = $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,99 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
/**
* As of PHP 5.3, the __toString() magic method can no longer accept arguments.
*
* Sister-sniff to `PHPCompatibility.MethodUse.ForbiddenToStringParameters`.
*
* PHP version 5.3
*
* @link https://www.php.net/manual/en/migration53.incompatible.php
* @link https://www.php.net/manual/en/language.oop5.magic.php#object.tostring
*
* @since 9.2.0
*/
class ForbiddenToStringParametersSniff extends Sniff
{
/**
* Valid scopes for the __toString() method to live in.
*
* @since 9.2.0
* @since 9.3.2 Visibility changed from `public` to `protected`.
*
* @var array
*/
protected $ooScopeTokens = array(
'T_CLASS' => true,
'T_INTERFACE' => true,
'T_TRAIT' => true,
'T_ANON_CLASS' => true,
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 9.2.0
*
* @return array
*/
public function register()
{
return array(\T_FUNCTION);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 9.2.0
*
* @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('5.3') === false) {
return;
}
$functionName = $phpcsFile->getDeclarationName($stackPtr);
if (strtolower($functionName) !== '__tostring') {
// Not the right function.
return;
}
if ($this->validDirectScope($phpcsFile, $stackPtr, $this->ooScopeTokens) === false) {
// Function, not method.
return;
}
$params = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr);
if (empty($params)) {
// Function declared without parameters.
return;
}
$phpcsFile->addError(
'The __toString() magic method can no longer accept arguments since PHP 5.3',
$stackPtr,
'Declared'
);
}
}
@@ -0,0 +1,122 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* Detect variable names forbidden to be used 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
*
* @link https://www.php.net/manual/en/migration71.incompatible.php#migration71.incompatible.lexical-names
* @link https://www.php.net/manual/en/functions.anonymous.php
*
* @since 7.1.4
*/
class ForbiddenVariableNamesInClosureUseSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 7.1.4
*
* @return array
*/
public function register()
{
return array(\T_USE);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 7.1.4
*
* @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,264 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* Detect closures and verify that the features used are supported.
*
* Version based checks:
* - Closures are available since PHP 5.3.
* - Closures can be declared as `static` since PHP 5.4.
* - Closures can use the `$this` variable within a class context since PHP 5.4.
* - Closures can use `self`/`parent`/`static` since PHP 5.4.
*
* Version independent checks:
* - Static closures don't have access to the `$this` variable.
* - Closures declared outside of a class context don't have access to the `$this`
* variable unless bound to an object.
*
* PHP version 5.3
* PHP version 5.4
*
* @link https://www.php.net/manual/en/functions.anonymous.php
* @link https://wiki.php.net/rfc/closures
* @link https://wiki.php.net/rfc/closures/object-extension
*
* @since 7.0.0
*/
class NewClosureSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 7.0.0
*
* @return array
*/
public function register()
{
return array(\T_CLOSURE);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 7.0.0
* @since 7.1.4 - Added check for closure being declared as static < 5.4.
* - Added check for use of `$this` variable in class context < 5.4.
* - Added check for use of `$this` variable in static closures (unsupported).
* - Added check for use of `$this` variable outside class context (unsupported).
* @since 8.2.0 Added check for use of `self`/`static`/`parent` < 5.4.
*
* @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 int|void Integer stack pointer to skip forward or void to continue
* normal file processing.
*/
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.
*
* @since 7.1.4
*
* @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.
*
* @since 7.1.4
*
* @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".
*
* @since 8.2.0
*
* @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,171 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* As of PHP 7.4, throwing exceptions from a `__toString()` method is allowed.
*
* PHP version 7.4
*
* @link https://wiki.php.net/rfc/tostring_exceptions
* @link https://www.php.net/manual/en/language.oop5.magic.php#object.tostring
*
* @since 9.2.0
*/
class NewExceptionsFromToStringSniff extends Sniff
{
/**
* Valid scopes for the __toString() method to live in.
*
* @since 9.2.0
* @since 9.3.0 Visibility changed from `public` to `protected`.
*
* @var array
*/
protected $ooScopeTokens = array(
'T_CLASS' => true,
'T_TRAIT' => true,
'T_ANON_CLASS' => true,
);
/**
* Tokens which should be ignored when they preface a function declaration
* when trying to find the docblock (if any).
*
* Array will be added to in the register() method.
*
* @since 9.3.0
*
* @var array
*/
private $docblockIgnoreTokens = array(
\T_WHITESPACE => \T_WHITESPACE,
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 9.2.0
*
* @return array
*/
public function register()
{
// Enhance the array of tokens to ignore for finding the docblock.
$this->docblockIgnoreTokens += Tokens::$methodPrefixes;
if (isset(Tokens::$phpcsCommentTokens)) {
$this->docblockIgnoreTokens += Tokens::$phpcsCommentTokens;
}
return array(\T_FUNCTION);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 9.2.0
*
* @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.3') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['scope_opener'], $tokens[$stackPtr]['scope_closer']) === false) {
// Abstract function, interface function, live coding or parse error.
return;
}
$functionName = $phpcsFile->getDeclarationName($stackPtr);
if (strtolower($functionName) !== '__tostring') {
// Not the right function.
return;
}
if ($this->validDirectScope($phpcsFile, $stackPtr, $this->ooScopeTokens) === false) {
// Function, not method.
return;
}
/*
* Examine the content of the function.
*/
$error = 'Throwing exceptions from __toString() was not allowed prior to PHP 7.4';
$throwPtr = $tokens[$stackPtr]['scope_opener'];
$errorThrown = false;
do {
$throwPtr = $phpcsFile->findNext(\T_THROW, ($throwPtr + 1), $tokens[$stackPtr]['scope_closer']);
if ($throwPtr === false) {
break;
}
$conditions = $tokens[$throwPtr]['conditions'];
$conditions = array_reverse($conditions, true);
$inTryCatch = false;
foreach ($conditions as $ptr => $type) {
if ($type === \T_TRY) {
$inTryCatch = true;
break;
}
if ($ptr === $stackPtr) {
// Don't check the conditions outside the function scope.
break;
}
}
if ($inTryCatch === false) {
$phpcsFile->addError($error, $throwPtr, 'Found');
$errorThrown = true;
}
} while (true);
if ($errorThrown === true) {
// We've already thrown an error for this method, no need to examine the docblock.
return;
}
/*
* Check whether the function has a docblock and if so, whether it contains a @throws tag.
*
* {@internal This can be partially replaced by the findCommentAboveFunction()
* utility function in due time.}
*/
$commentEnd = $phpcsFile->findPrevious($this->docblockIgnoreTokens, ($stackPtr - 1), null, true);
if ($commentEnd === false || $tokens[$commentEnd]['code'] !== \T_DOC_COMMENT_CLOSE_TAG) {
return;
}
$commentStart = $tokens[$commentEnd]['comment_opener'];
foreach ($tokens[$commentStart]['comment_tags'] as $tag) {
if ($tokens[$tag]['content'] !== '@throws') {
continue;
}
// Found a throws tag.
$phpcsFile->addError($error, $stackPtr, 'ThrowsTagFoundInDocblock');
break;
}
}
}
@@ -0,0 +1,169 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* Nullable parameter type declarations and return types are available since PHP 7.1.
*
* PHP version 7.1
*
* @link https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.nullable-types
* @link https://wiki.php.net/rfc/nullable_types
* @link https://www.php.net/manual/en/functions.arguments.php#example-146
*
* @since 7.0.7
*/
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.}
*
* @since 7.0.7
*
* @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.
*
* @since 7.0.7
*
* @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.
*
* @since 7.0.7
*
* @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.
*
* @since 7.0.7
*
* @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,237 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\AbstractNewFeatureSniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
/**
* Detect and verify the use of parameter type declarations in function declarations.
*
* Parameter type declarations - class/interface names only - is available since PHP 5.0.
* - Since PHP 5.1, the `array` keyword can be used.
* - Since PHP 5.2, `self` and `parent` can be used. Previously, those were interpreted as
* class names.
* - Since PHP 5.4, the `callable` keyword.
* - Since PHP 7.0, scalar type declarations are available.
* - Since PHP 7.1, the `iterable` pseudo-type is available.
* - Since PHP 7.2, the generic `object` type is available.
*
* Additionally, this sniff does a cursory check for typical invalid type declarations,
* such as:
* - `boolean` (should be `bool`), `integer` (should be `int`) and `static`.
* - `self`/`parent` as type declaration used outside class context throws a fatal error since PHP 7.0.
*
* PHP version 5.0+
*
* @link https://www.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration
* @link https://wiki.php.net/rfc/callable
* @link https://wiki.php.net/rfc/scalar_type_hints_v5
* @link https://wiki.php.net/rfc/iterable
* @link https://wiki.php.net/rfc/object-typehint
*
* @since 7.0.0
* @since 7.1.0 Now extends the `AbstractNewFeatureSniff` instead of the base `Sniff` class.
* @since 9.0.0 Renamed from `NewScalarTypeDeclarationsSniff` to `NewParamTypeDeclarationsSniff`.
*/
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.
*
* @since 7.0.0
* @since 7.0.3 Now lists all param type declarations, not just the PHP 7+ scalar ones.
*
* @var array(string => array(string => bool))
*/
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.
*
* @since 7.0.3
*
* @var array(string => string)
*/
protected $invalidTypes = array(
'static' => 'self',
'boolean' => 'bool',
'integer' => 'int',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 7.0.0
* @since 7.1.3 Now also checks closures.
*
* @return array
*/
public function register()
{
return array(
\T_FUNCTION,
\T_CLOSURE,
);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 7.0.0
* @since 7.0.3 - Added check for non-scalar type declarations.
* - Added check for invalid type declarations.
* - Added check for usage of `self` type declaration outside
* class scope.
* @since 8.2.0 Added check for `parent` type declaration outside class scope.
*
* @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.
*
* @since 7.1.0
*
* @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.
*
* @since 7.1.0
*
* @return string
*/
protected function getErrorMsgTemplate()
{
return "'%s' type declaration is not present in PHP version %s or earlier";
}
}
@@ -0,0 +1,194 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\AbstractNewFeatureSniff;
use PHP_CodeSniffer_File as File;
/**
* Detect and verify the use of return type declarations in function declarations.
*
* Return type declarations are available since PHP 7.0.
* - Since PHP 7.1, the `iterable` and `void` pseudo-types are available.
* - Since PHP 7.2, the generic `object` type is available.
*
* PHP version 7.0+
*
* @link https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.return-type-declarations
* @link https://www.php.net/manual/en/functions.returning-values.php#functions.returning-values.type-declaration
* @link https://wiki.php.net/rfc/return_types
* @link https://wiki.php.net/rfc/iterable
* @link https://wiki.php.net/rfc/void_return_type
* @link https://wiki.php.net/rfc/object-typehint
*
* @since 7.0.0
* @since 7.1.0 Now extends the `AbstractNewFeatureSniff` instead of the base `Sniff` class.
* @since 7.1.2 Renamed from `NewScalarReturnTypeDeclarationsSniff` to `NewReturnTypeDeclarationsSniff`.
*/
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.
*
* @since 7.0.0
*
* @var array(string => array(string => bool))
*/
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.
*
* @since 7.0.0
* @since 7.1.2 Now also checks based on the function and closure keywords.
*
* @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.
*
* @since 7.0.0
*
* @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.
*
* @since 7.1.0
*
* @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.
*
* @since 7.1.0
*
* @return string
*/
protected function getErrorMsgTemplate()
{
return '%s return type is not present in PHP version %s or earlier';
}
}
@@ -0,0 +1,216 @@
<?php
/**
* PHPCompatibility, an external standard for PHP_CodeSniffer.
*
* @package PHPCompatibility
* @copyright 2012-2019 PHPCompatibility Contributors
* @license https://opensource.org/licenses/LGPL-3.0 LGPL3
* @link https://github.com/PHPCompatibility/PHPCompatibility
*/
namespace PHPCompatibility\Sniffs\FunctionDeclarations;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
/**
* Verifies the use of the correct visibility and static properties of magic methods.
*
* The requirements have always existed, but as of PHP 5.3, a warning will be thrown
* when magic methods have the wrong modifiers.
*
* PHP version 5.3
*
* @link https://www.php.net/manual/en/language.oop5.magic.php
*
* @since 5.5
* @since 5.6 Now extends the base `Sniff` class.
*/
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.
*
* @since 5.5
* @since 5.6 The array format has changed to allow the sniff to also verify the
* use of the correct visibility for a magic method.
*
* @var array(string)
*/
protected $magicMethods = array(
'__construct' => array(
'static' => false,
),
'__destruct' => array(
'visibility' => 'public',
'static' => false,
),
'__clone' => array(
'static' => false,
),
'__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(
'visibility' => 'public',
'static' => true,
),
'__debuginfo' => array(
'visibility' => 'public',
'static' => false,
),
'__invoke' => array(
'visibility' => 'public',
'static' => false,
),
'__serialize' => array(
'visibility' => 'public',
'static' => false,
),
'__unserialize' => array(
'visibility' => 'public',
'static' => false,
),
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 5.5
* @since 5.6 Now also checks traits.
* @since 7.1.4 Now also checks anonymous classes.
*
* @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.
*
* @since 5.5
*
* @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;
}
}
}