基础代码

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,238 @@
<?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\ControlStructures;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* Detect use of `continue` in `switch` control structures.
*
* As of PHP 7.3, PHP will throw a warning when `continue` is used to target a `switch`
* control structure.
* The sniff takes numeric arguments used with `continue` into account.
*
* PHP version 7.3
*
* @link https://www.php.net/manual/en/migration73.incompatible.php#migration73.incompatible.core.continue-targeting-switch
* @link https://wiki.php.net/rfc/continue_on_switch_deprecation
* @link https://github.com/php/php-src/commit/04e3523b7d095341f65ed5e71a3cac82fca690e4
* (actual implementation which is different from the RFC).
* @link https://www.php.net/manual/en/control-structures.switch.php
*
* @since 8.2.0
*/
class DiscouragedSwitchContinueSniff extends Sniff
{
/**
* Token codes of control structures which can be targeted using continue.
*
* @since 8.2.0
*
* @var array
*/
protected $loopStructures = array(
\T_FOR => \T_FOR,
\T_FOREACH => \T_FOREACH,
\T_WHILE => \T_WHILE,
\T_DO => \T_DO,
\T_SWITCH => \T_SWITCH,
);
/**
* Tokens which start a new case within a switch.
*
* @since 8.2.0
*
* @var array
*/
protected $caseTokens = array(
\T_CASE => \T_CASE,
\T_DEFAULT => \T_DEFAULT,
);
/**
* Token codes which are accepted to determine the level for the continue.
*
* This array is enriched with the arithmetic operators in the register() method.
*
* @since 8.2.0
*
* @var array
*/
protected $acceptedLevelTokens = array(
\T_LNUMBER => \T_LNUMBER,
\T_OPEN_PARENTHESIS => \T_OPEN_PARENTHESIS,
\T_CLOSE_PARENTHESIS => \T_CLOSE_PARENTHESIS,
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 8.2.0
*
* @return array
*/
public function register()
{
$this->acceptedLevelTokens += Tokens::$arithmeticTokens;
$this->acceptedLevelTokens += Tokens::$emptyTokens;
return array(\T_SWITCH);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 8.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('7.3') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['scope_opener'], $tokens[$stackPtr]['scope_closer']) === false) {
return;
}
$switchOpener = $tokens[$stackPtr]['scope_opener'];
$switchCloser = $tokens[$stackPtr]['scope_closer'];
// Quick check whether we need to bother with the more complex logic.
$hasContinue = $phpcsFile->findNext(\T_CONTINUE, ($switchOpener + 1), $switchCloser);
if ($hasContinue === false) {
return;
}
$caseDefault = $switchOpener;
do {
$caseDefault = $phpcsFile->findNext($this->caseTokens, ($caseDefault + 1), $switchCloser);
if ($caseDefault === false) {
break;
}
if (isset($tokens[$caseDefault]['scope_opener']) === false) {
// Unknown start of the case, skip.
continue;
}
$caseOpener = $tokens[$caseDefault]['scope_opener'];
$nextCaseDefault = $phpcsFile->findNext($this->caseTokens, ($caseDefault + 1), $switchCloser);
if ($nextCaseDefault === false) {
$caseCloser = $switchCloser;
} else {
$caseCloser = $nextCaseDefault;
}
// Check for unscoped control structures within the case.
$controlStructure = $caseOpener;
$doCount = 0;
while (($controlStructure = $phpcsFile->findNext($this->loopStructures, ($controlStructure + 1), $caseCloser)) !== false) {
if ($tokens[$controlStructure]['code'] === \T_DO) {
$doCount++;
}
if (isset($tokens[$controlStructure]['scope_opener'], $tokens[$controlStructure]['scope_closer']) === false) {
if ($tokens[$controlStructure]['code'] === \T_WHILE && $doCount > 0) {
// While in a do-while construct.
$doCount--;
continue;
}
// Control structure without braces found within the case, ignore this case.
continue 2;
}
}
// Examine the contents of the case.
$continue = $caseOpener;
do {
$continue = $phpcsFile->findNext(\T_CONTINUE, ($continue + 1), $caseCloser);
if ($continue === false) {
break;
}
$nextSemicolon = $phpcsFile->findNext(array(\T_SEMICOLON, \T_CLOSE_TAG), ($continue + 1), $caseCloser);
$codeString = '';
for ($i = ($continue + 1); $i < $nextSemicolon; $i++) {
if (isset($this->acceptedLevelTokens[$tokens[$i]['code']]) === false) {
// Function call/variable or other token which make numeric level impossible to determine.
continue 2;
}
if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === true) {
continue;
}
$codeString .= $tokens[$i]['content'];
}
$level = null;
if ($codeString !== '') {
if (is_numeric($codeString)) {
$level = (int) $codeString;
} else {
// With the above logic, the string can only contain digits and operators, eval!
$level = eval("return ( $codeString );");
}
}
if (isset($level) === false || $level === 0) {
$level = 1;
}
// Examine which control structure is being targeted by the continue statement.
if (isset($tokens[$continue]['conditions']) === false) {
continue;
}
$conditions = array_reverse($tokens[$continue]['conditions'], true);
// PHPCS adds more structures to the conditions array than we want to take into
// consideration, so clean up the array.
foreach ($conditions as $tokenPtr => $tokenCode) {
if (isset($this->loopStructures[$tokenCode]) === false) {
unset($conditions[$tokenPtr]);
}
}
$targetCondition = \array_slice($conditions, ($level - 1), 1, true);
if (empty($targetCondition)) {
continue;
}
$conditionToken = key($targetCondition);
if ($conditionToken === $stackPtr) {
$phpcsFile->addWarning(
"Targeting a 'switch' control structure with a 'continue' statement is strongly discouraged and will throw a warning as of PHP 7.3.",
$continue,
'Found'
);
}
} while ($continue < $caseCloser);
} while ($caseDefault < $switchCloser);
}
}
@@ -0,0 +1,116 @@
<?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\ControlStructures;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
/**
* Detect using `break` and/or `continue` statements outside of a looping structure.
*
* PHP version 7.0
*
* @link https://www.php.net/manual/en/migration70.incompatible.php#migration70.incompatible.other.break-continue
* @link https://www.php.net/manual/en/control-structures.break.php
* @link https://www.php.net/manual/en/control-structures.continue.php
*
* @since 7.0.7
*/
class ForbiddenBreakContinueOutsideLoopSniff extends Sniff
{
/**
* Token codes of control structure in which usage of break/continue is valid.
*
* @since 7.0.7
*
* @var array
*/
protected $validLoopStructures = array(
\T_FOR => true,
\T_FOREACH => true,
\T_WHILE => true,
\T_DO => true,
\T_SWITCH => true,
);
/**
* Token codes which did not correctly get a condition assigned in older PHPCS versions.
*
* @since 7.0.7
*
* @var array
*/
protected $backCompat = array(
\T_CASE => true,
\T_DEFAULT => true,
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 7.0.7
*
* @return array
*/
public function register()
{
return array(
\T_BREAK,
\T_CONTINUE,
);
}
/**
* 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)
{
$tokens = $phpcsFile->getTokens();
$token = $tokens[$stackPtr];
// Check if the break/continue is within a valid loop structure.
if (empty($token['conditions']) === false) {
foreach ($token['conditions'] as $tokenCode) {
if (isset($this->validLoopStructures[$tokenCode]) === true) {
return;
}
}
} else {
// Deal with older PHPCS versions.
if (isset($token['scope_condition']) === true && isset($this->backCompat[$tokens[$token['scope_condition']]['code']]) === true) {
return;
}
}
// If we're still here, no valid loop structure container has been found, so throw an error.
$error = "Using '%s' outside of a loop or switch structure is invalid";
$isError = false;
$errorCode = 'Found';
$data = array($token['content']);
if ($this->supportsAbove('7.0')) {
$error .= ' and will throw a fatal error since PHP 7.0';
$isError = true;
$errorCode = 'FatalError';
}
$this->addMessage($phpcsFile, $error, $stackPtr, $isError, $errorCode, $data);
}
}
@@ -0,0 +1,110 @@
<?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\ControlStructures;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* Detects using 0 and variable numeric arguments on `break` and `continue` statements.
*
* This sniff checks for:
* - Using `break` and/or `continue` with a variable as the numeric argument.
* - Using `break` and/or `continue` with a zero - 0 - as the numeric argument.
*
* PHP version 5.4
*
* @link https://www.php.net/manual/en/migration54.incompatible.php
* @link https://www.php.net/manual/en/control-structures.break.php
* @link https://www.php.net/manual/en/control-structures.continue.php
*
* @since 5.5
* @since 5.6 Now extends the base `Sniff` class.
*/
class ForbiddenBreakContinueVariableArgumentsSniff extends Sniff
{
/**
* Error types this sniff handles for forbidden break/continue arguments.
*
* Array key is the error code. Array value will be used as part of the error message.
*
* @since 7.0.5
* @since 7.1.0 Changed from class constants to property.
*
* @var array
*/
private $errorTypes = array(
'variableArgument' => 'a variable argument',
'zeroArgument' => '0 as an argument',
);
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 5.5
*
* @return array
*/
public function register()
{
return array(\T_BREAK, \T_CONTINUE);
}
/**
* 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)
{
if ($this->supportsAbove('5.4') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
$nextSemicolonToken = $phpcsFile->findNext(array(\T_SEMICOLON, \T_CLOSE_TAG), ($stackPtr), null, false);
$errorType = '';
for ($curToken = $stackPtr + 1; $curToken < $nextSemicolonToken; $curToken++) {
if ($tokens[$curToken]['type'] === 'T_STRING') {
// If the next non-whitespace token after the string
// is an opening parenthesis then it's a function call.
$openBracket = $phpcsFile->findNext(Tokens::$emptyTokens, $curToken + 1, null, true);
if ($tokens[$openBracket]['code'] === \T_OPEN_PARENTHESIS) {
$errorType = 'variableArgument';
break;
}
} elseif (\in_array($tokens[$curToken]['type'], array('T_VARIABLE', 'T_FUNCTION', 'T_CLOSURE'), true)) {
$errorType = 'variableArgument';
break;
} elseif ($tokens[$curToken]['type'] === 'T_LNUMBER' && $tokens[$curToken]['content'] === '0') {
$errorType = 'zeroArgument';
break;
}
}
if ($errorType !== '') {
$error = 'Using %s on break or continue is forbidden since PHP 5.4';
$errorCode = $errorType . 'Found';
$data = array($this->errorTypes[$errorType]);
$phpcsFile->addError($error, $stackPtr, $errorCode, $data);
}
}
}
@@ -0,0 +1,81 @@
<?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\ControlStructures;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
/**
* Switch statements can not have multiple default blocks since PHP 7.0.
*
* PHP version 7.0
*
* @link https://wiki.php.net/rfc/switch.default.multiple
* @link https://www.php.net/manual/en/control-structures.switch.php
*
* @since 7.0.0
*/
class ForbiddenSwitchWithMultipleDefaultBlocksSniff 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_SWITCH);
}
/**
* 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();
if (isset($tokens[$stackPtr]['scope_closer']) === false) {
return;
}
$defaultToken = $stackPtr;
$defaultCount = 0;
$targetLevel = $tokens[$stackPtr]['level'] + 1;
while ($defaultCount < 2 && ($defaultToken = $phpcsFile->findNext(array(\T_DEFAULT), $defaultToken + 1, $tokens[$stackPtr]['scope_closer'])) !== false) {
// Same level or one below (= two default cases after each other).
if ($tokens[$defaultToken]['level'] === $targetLevel || $tokens[$defaultToken]['level'] === ($targetLevel + 1)) {
$defaultCount++;
}
}
if ($defaultCount > 1) {
$phpcsFile->addError(
'Switch statements can not have multiple default blocks since PHP 7.0',
$stackPtr,
'Found'
);
}
}
}
@@ -0,0 +1,378 @@
<?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\ControlStructures;
use PHPCompatibility\AbstractNewFeatureSniff;
use PHPCompatibility\PHPCSHelper;
use PHP_CodeSniffer_File as File;
use PHP_CodeSniffer_Tokens as Tokens;
/**
* Check for valid execution directives set with `declare()`.
*
* The sniff contains three distinct checks:
* - Check if the execution directive used is valid. PHP currently only supports
* three execution directives.
* - Check if the execution directive used is available in the PHP versions
* for which support is being checked.
* In the case of the `encoding` directive on PHP 5.3, support is conditional
* on the `--enable-zend-multibyte` compilation option. This will be indicated as such.
* - Check whether the value for the directive is valid.
*
* PHP version All
*
* @link https://www.php.net/manual/en/control-structures.declare.php
* @link https://wiki.php.net/rfc/scalar_type_hints_v5#strict_types_declare_directive
*
* @since 7.0.3
* @since 7.1.0 Now extends the `AbstractNewFeatureSniff` instead of the base `Sniff` class.
*/
class NewExecutionDirectivesSniff extends AbstractNewFeatureSniff
{
/**
* A list of new execution directives
*
* The array lists : version number with false (not present) or true (present).
* If the execution order is conditional, add the condition as a string to the version nr.
* If's sufficient to list the first version where the execution directive appears.
*
* @since 7.0.3
*
* @var array(string => array(string => bool|string|array))
*/
protected $newDirectives = array(
'ticks' => array(
'3.1' => false,
'4.0' => true,
'valid_value_callback' => 'isNumeric',
),
'encoding' => array(
'5.2' => false,
'5.3' => '--enable-zend-multibyte', // Directive ignored unless.
'5.4' => true,
'valid_value_callback' => 'validEncoding',
),
'strict_types' => array(
'5.6' => false,
'7.0' => true,
'valid_values' => array(1),
),
);
/**
* Tokens to ignore when trying to find the value for the directive.
*
* @since 7.0.3
*
* @var array
*/
protected $ignoreTokens = array();
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 7.0.3
*
* @return array
*/
public function register()
{
$this->ignoreTokens = Tokens::$emptyTokens;
$this->ignoreTokens[\T_EQUAL] = \T_EQUAL;
return array(\T_DECLARE);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 7.0.3
*
* @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();
if (isset($tokens[$stackPtr]['parenthesis_opener'], $tokens[$stackPtr]['parenthesis_closer']) === true) {
$openParenthesis = $tokens[$stackPtr]['parenthesis_opener'];
$closeParenthesis = $tokens[$stackPtr]['parenthesis_closer'];
} else {
if (version_compare(PHPCSHelper::getVersion(), '2.3.4', '>=')) {
return;
}
// Deal with PHPCS 2.3.0-2.3.3 which do not yet set the parenthesis properly for declare statements.
$openParenthesis = $phpcsFile->findNext(\T_OPEN_PARENTHESIS, ($stackPtr + 1), null, false, null, true);
if ($openParenthesis === false || isset($tokens[$openParenthesis]['parenthesis_closer']) === false) {
return;
}
$closeParenthesis = $tokens[$openParenthesis]['parenthesis_closer'];
}
$directivePtr = $phpcsFile->findNext(\T_STRING, ($openParenthesis + 1), $closeParenthesis, false);
if ($directivePtr === false) {
return;
}
$directiveContent = $tokens[$directivePtr]['content'];
if (isset($this->newDirectives[$directiveContent]) === false) {
$error = 'Declare can only be used with the directives %s. Found: %s';
$data = array(
implode(', ', array_keys($this->newDirectives)),
$directiveContent,
);
$phpcsFile->addError($error, $stackPtr, 'InvalidDirectiveFound', $data);
} else {
// Check for valid directive for version.
$itemInfo = array(
'name' => $directiveContent,
);
$this->handleFeature($phpcsFile, $stackPtr, $itemInfo);
// Check for valid directive value.
$valuePtr = $phpcsFile->findNext($this->ignoreTokens, $directivePtr + 1, $closeParenthesis, true);
if ($valuePtr === false) {
return;
}
$this->addWarningOnInvalidValue($phpcsFile, $valuePtr, $directiveContent);
}
}
/**
* Determine whether an error/warning should be thrown for an item based on collected information.
*
* @since 7.1.0
*
* @param array $errorInfo Detail information about an item.
*
* @return bool
*/
protected function shouldThrowError(array $errorInfo)
{
return ($errorInfo['not_in_version'] !== '' || $errorInfo['conditional_version'] !== '');
}
/**
* 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->newDirectives[$itemInfo['name']];
}
/**
* Get an array of the non-PHP-version array keys used in a sub-array.
*
* @since 7.1.0
*
* @return array
*/
protected function getNonVersionArrayKeys()
{
return array(
'valid_value_callback',
'valid_values',
);
}
/**
* Retrieve the relevant detail (version) information for use in an error message.
*
* @since 7.1.0
*
* @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['conditional_version'] = '';
$errorInfo['condition'] = '';
$versionArray = $this->getVersionArray($itemArray);
if (empty($versionArray) === false) {
foreach ($versionArray as $version => $present) {
if (\is_string($present) === true && $this->supportsBelow($version) === true) {
// We cannot test for compilation option (ok, except by scraping the output of phpinfo...).
$errorInfo['conditional_version'] = $version;
$errorInfo['condition'] = $present;
}
}
}
return $errorInfo;
}
/**
* Get the error message template for this sniff.
*
* @since 7.1.0
*
* @return string
*/
protected function getErrorMsgTemplate()
{
return 'Directive ' . parent::getErrorMsgTemplate();
}
/**
* Generates the error or warning for this item.
*
* @since 7.0.3
* @since 7.1.0 This method now overloads the method from the `AbstractNewFeatureSniff` class.
* - Renamed from `maybeAddError()` to `addError()`.
* - Changed visibility from `protected` to `public`.
*
* @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the relevant token in
* the stack.
* @param array $itemInfo Base information about the item.
* @param array $errorInfo Array with detail (version) information
* relevant to the item.
*
* @return void
*/
public function addError(File $phpcsFile, $stackPtr, array $itemInfo, array $errorInfo)
{
if ($errorInfo['not_in_version'] !== '') {
parent::addError($phpcsFile, $stackPtr, $itemInfo, $errorInfo);
} elseif ($errorInfo['conditional_version'] !== '') {
$error = 'Directive %s is present in PHP version %s but will be disregarded unless PHP is compiled with %s';
$errorCode = $this->stringToErrorCode($itemInfo['name']) . 'WithConditionFound';
$data = array(
$itemInfo['name'],
$errorInfo['conditional_version'],
$errorInfo['condition'],
);
$phpcsFile->addWarning($error, $stackPtr, $errorCode, $data);
}
}
/**
* Generates a error or warning for this sniff.
*
* @since 7.0.3
* @since 7.0.6 Renamed from `addErrorOnInvalidValue()` to `addWarningOnInvalidValue()`.
*
* @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param int $stackPtr The position of the execution directive value
* in the token array.
* @param string $directive The directive.
*
* @return void
*/
protected function addWarningOnInvalidValue(File $phpcsFile, $stackPtr, $directive)
{
$tokens = $phpcsFile->getTokens();
$value = $tokens[$stackPtr]['content'];
if (isset(Tokens::$stringTokens[$tokens[$stackPtr]['code']]) === true) {
$value = $this->stripQuotes($value);
}
$isError = false;
if (isset($this->newDirectives[$directive]['valid_values'])) {
if (\in_array($value, $this->newDirectives[$directive]['valid_values']) === false) {
$isError = true;
}
} elseif (isset($this->newDirectives[$directive]['valid_value_callback'])) {
$valid = \call_user_func(array($this, $this->newDirectives[$directive]['valid_value_callback']), $value);
if ($valid === false) {
$isError = true;
}
}
if ($isError === true) {
$error = 'The execution directive %s does not seem to have a valid value. Please review. Found: %s';
$errorCode = $this->stringToErrorCode($directive) . 'InvalidValueFound';
$data = array(
$directive,
$value,
);
$phpcsFile->addWarning($error, $stackPtr, $errorCode, $data);
}
}
/**
* Check whether a value is numeric.
*
* Callback function to test whether the value for an execution directive is valid.
*
* @since 7.0.3
*
* @param mixed $value The value to test.
*
* @return bool
*/
protected function isNumeric($value)
{
return is_numeric($value);
}
/**
* Check whether a value is a valid encoding.
*
* Callback function to test whether the value for an execution directive is valid.
*
* @since 7.0.3
*
* @param mixed $value The value to test.
*
* @return bool
*/
protected function validEncoding($value)
{
static $encodings;
if (isset($encodings) === false && function_exists('mb_list_encodings')) {
$encodings = mb_list_encodings();
}
if (empty($encodings) || \is_array($encodings) === false) {
// If we can't test the encoding, let it pass through.
return true;
}
return \in_array($value, $encodings, true);
}
}
@@ -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\ControlStructures;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
/**
* Detect `foreach` expression referencing.
*
* Before PHP 5.5.0, referencing `$value` in a `foreach` was only possible
* if the iterated array could be referenced (i.e. if it is a variable).
*
* PHP version 5.5
*
* @link https://www.php.net/manual/en/control-structures.foreach.php
*
* @since 9.0.0
*/
class NewForeachExpressionReferencingSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 9.0.0
*
* @return array
*/
public function register()
{
return array(\T_FOREACH);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 9.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->supportsBelow('5.4') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['parenthesis_opener'], $tokens[$stackPtr]['parenthesis_closer']) === false) {
return;
}
$opener = $tokens[$stackPtr]['parenthesis_opener'];
$closer = $tokens[$stackPtr]['parenthesis_closer'];
$asToken = $phpcsFile->findNext(\T_AS, ($opener + 1), $closer);
if ($asToken === false) {
return;
}
/*
* Note: referencing $key is not allowed in any version, so this should only find referenced $values.
* If it does find a referenced key, it would be a parse error anyway.
*/
$hasReference = $phpcsFile->findNext(\T_BITWISE_AND, ($asToken + 1), $closer);
if ($hasReference === false) {
return;
}
$nestingLevel = 0;
if ($asToken !== ($opener + 1) && isset($tokens[$opener + 1]['nested_parenthesis'])) {
$nestingLevel = \count($tokens[$opener + 1]['nested_parenthesis']);
}
if ($this->isVariable($phpcsFile, ($opener + 1), $asToken, $nestingLevel) === true) {
return;
}
// Non-variable detected before the `as` keyword.
$phpcsFile->addError(
'Referencing $value is only possible if the iterated array is a variable in PHP 5.4 or earlier.',
$hasReference,
'Found'
);
}
}
@@ -0,0 +1,84 @@
<?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\ControlStructures;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
/**
* Detect unpacking nested arrays with `list()` in a `foreach()` as available since PHP 5.5.
*
* PHP version 5.5
*
* @link https://www.php.net/manual/en/migration55.new-features.php#migration55.new-features.foreach-list
* @link https://wiki.php.net/rfc/foreachlist
* @link https://www.php.net/manual/en/control-structures.foreach.php#control-structures.foreach.list
*
* @since 9.0.0
*/
class NewListInForeachSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 9.0.0
*
* @return array
*/
public function register()
{
return array(\T_FOREACH);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @since 9.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->supportsBelow('5.4') === false) {
return;
}
$tokens = $phpcsFile->getTokens();
if (isset($tokens[$stackPtr]['parenthesis_opener'], $tokens[$stackPtr]['parenthesis_closer']) === false) {
return;
}
$opener = $tokens[$stackPtr]['parenthesis_opener'];
$closer = $tokens[$stackPtr]['parenthesis_closer'];
$asToken = $phpcsFile->findNext(\T_AS, ($opener + 1), $closer);
if ($asToken === false) {
return;
}
$hasList = $phpcsFile->findNext(array(\T_LIST, \T_OPEN_SHORT_ARRAY), ($asToken + 1), $closer);
if ($hasList === false) {
return;
}
$phpcsFile->addError(
'Unpacking nested arrays with list() in a foreach is not supported in PHP 5.4 or earlier.',
$hasList,
'Found'
);
}
}
@@ -0,0 +1,78 @@
<?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\ControlStructures;
use PHPCompatibility\Sniff;
use PHP_CodeSniffer_File as File;
/**
* Catching multiple exception types in one statement is available since PHP 7.1.
*
* PHP version 7.1
*
* @link https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.mulit-catch-exception-handling
* @link https://wiki.php.net/rfc/multiple-catch
* @link https://www.php.net/manual/en/language.exceptions.php#language.exceptions.catch
*
* @since 7.0.7
*/
class NewMultiCatchSniff extends Sniff
{
/**
* Returns an array of tokens this test wants to listen for.
*
* @since 7.0.7
*
* @return array
*/
public function register()
{
return array(\T_CATCH);
}
/**
* 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();
$token = $tokens[$stackPtr];
// Bow out during live coding.
if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === false) {
return;
}
$hasBitwiseOr = $phpcsFile->findNext(\T_BITWISE_OR, $token['parenthesis_opener'], $token['parenthesis_closer']);
if ($hasBitwiseOr === false) {
return;
}
$phpcsFile->addError(
'Catching multiple exceptions within one statement is not supported in PHP 7.0 or earlier.',
$hasBitwiseOr,
'Found'
);
}
}