NewConstantArraysUsingConstSniff.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /**
  3. * PHPCompatibility, an external standard for PHP_CodeSniffer.
  4. *
  5. * @package PHPCompatibility
  6. * @copyright 2012-2019 PHPCompatibility Contributors
  7. * @license https://opensource.org/licenses/LGPL-3.0 LGPL3
  8. * @link https://github.com/PHPCompatibility/PHPCompatibility
  9. */
  10. namespace PHPCompatibility\Sniffs\InitialValue;
  11. use PHPCompatibility\Sniff;
  12. use PHP_CodeSniffer_File as File;
  13. /**
  14. * Detect declaration of constants using the `const` keyword with a (constant) array value
  15. * as supported since PHP 5.6.
  16. *
  17. * PHP version 5.6
  18. *
  19. * @link https://wiki.php.net/rfc/const_scalar_exprs
  20. * @link https://www.php.net/manual/en/language.constants.syntax.php
  21. *
  22. * @since 7.1.4
  23. * @since 9.0.0 Renamed from `ConstantArraysUsingConstSniff` to `NewConstantArraysUsingConstSniff`.
  24. */
  25. class NewConstantArraysUsingConstSniff extends Sniff
  26. {
  27. /**
  28. * Returns an array of tokens this test wants to listen for.
  29. *
  30. * @since 7.1.4
  31. *
  32. * @return array
  33. */
  34. public function register()
  35. {
  36. return array(\T_CONST);
  37. }
  38. /**
  39. * Processes this test, when one of its tokens is encountered.
  40. *
  41. * @since 7.1.4
  42. *
  43. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  44. * @param int $stackPtr The position of the current token in the
  45. * stack passed in $tokens.
  46. *
  47. * @return void
  48. */
  49. public function process(File $phpcsFile, $stackPtr)
  50. {
  51. if ($this->supportsBelow('5.5') !== true) {
  52. return;
  53. }
  54. $tokens = $phpcsFile->getTokens();
  55. $find = array(
  56. \T_ARRAY => \T_ARRAY,
  57. \T_OPEN_SHORT_ARRAY => \T_OPEN_SHORT_ARRAY,
  58. );
  59. while (($hasArray = $phpcsFile->findNext($find, ($stackPtr + 1), null, false, null, true)) !== false) {
  60. $phpcsFile->addError(
  61. 'Constant arrays using the "const" keyword are not allowed in PHP 5.5 or earlier',
  62. $hasArray,
  63. 'Found'
  64. );
  65. // Skip past the content of the array.
  66. $stackPtr = $hasArray;
  67. if ($tokens[$hasArray]['code'] === \T_OPEN_SHORT_ARRAY && isset($tokens[$hasArray]['bracket_closer'])) {
  68. $stackPtr = $tokens[$hasArray]['bracket_closer'];
  69. } elseif ($tokens[$hasArray]['code'] === \T_ARRAY && isset($tokens[$hasArray]['parenthesis_closer'])) {
  70. $stackPtr = $tokens[$hasArray]['parenthesis_closer'];
  71. }
  72. }
  73. }
  74. }