NewConstVisibilitySniff.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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\Classes;
  11. use PHPCompatibility\Sniff;
  12. use PHP_CodeSniffer_File as File;
  13. use PHP_CodeSniffer_Tokens as Tokens;
  14. /**
  15. * Visibility for class constants is available since PHP 7.1.
  16. *
  17. * PHP version 7.1
  18. *
  19. * @link https://wiki.php.net/rfc/class_const_visibility
  20. * @link https://www.php.net/manual/en/language.oop5.constants.php#language.oop5.basic.class.this
  21. *
  22. * @since 7.0.7
  23. */
  24. class NewConstVisibilitySniff extends Sniff
  25. {
  26. /**
  27. * Returns an array of tokens this test wants to listen for.
  28. *
  29. * @since 7.0.7
  30. *
  31. * @return array
  32. */
  33. public function register()
  34. {
  35. return array(\T_CONST);
  36. }
  37. /**
  38. * Processes this test, when one of its tokens is encountered.
  39. *
  40. * @since 7.0.7
  41. *
  42. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  43. * @param int $stackPtr The position of the current token
  44. * in the stack passed in $tokens.
  45. *
  46. * @return void
  47. */
  48. public function process(File $phpcsFile, $stackPtr)
  49. {
  50. if ($this->supportsBelow('7.0') === false) {
  51. return;
  52. }
  53. $tokens = $phpcsFile->getTokens();
  54. $prevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true, null, true);
  55. // Is the previous token a visibility indicator ?
  56. if ($prevToken === false || isset(Tokens::$scopeModifiers[$tokens[$prevToken]['code']]) === false) {
  57. return;
  58. }
  59. // Is this a class constant ?
  60. if ($this->isClassConstant($phpcsFile, $stackPtr) === false) {
  61. // This may be a constant declaration in the global namespace with visibility,
  62. // but that would throw a parse error, i.e. not our concern.
  63. return;
  64. }
  65. $phpcsFile->addError(
  66. 'Visibility indicators for class constants are not supported in PHP 7.0 or earlier. Found "%s const"',
  67. $stackPtr,
  68. 'Found',
  69. array($tokens[$prevToken]['content'])
  70. );
  71. }
  72. }