NewMagicClassConstantSniff.php 2.2 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\Constants;
  11. use PHPCompatibility\Sniff;
  12. use PHP_CodeSniffer_File as File;
  13. use PHP_CodeSniffer_Tokens as Tokens;
  14. /**
  15. * Detect usage of the magic `::class` constant introduced in PHP 5.5.
  16. *
  17. * The special `ClassName::class` constant is available as of PHP 5.5.0, and allows
  18. * for fully qualified class name resolution at compile time.
  19. *
  20. * PHP version 5.5
  21. *
  22. * @link https://wiki.php.net/rfc/class_name_scalars
  23. * @link https://www.php.net/manual/en/language.oop5.constants.php#example-186
  24. *
  25. * @since 7.1.4
  26. * @since 7.1.5 Removed the incorrect checks against invalid usage of the constant.
  27. */
  28. class NewMagicClassConstantSniff extends Sniff
  29. {
  30. /**
  31. * Returns an array of tokens this test wants to listen for.
  32. *
  33. * @since 7.1.4
  34. *
  35. * @return array
  36. */
  37. public function register()
  38. {
  39. return array(\T_STRING);
  40. }
  41. /**
  42. * Processes this test, when one of its tokens is encountered.
  43. *
  44. * @since 7.1.4
  45. *
  46. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  47. * @param int $stackPtr The position of the current token in the
  48. * stack passed in $tokens.
  49. *
  50. * @return void
  51. */
  52. public function process(File $phpcsFile, $stackPtr)
  53. {
  54. if ($this->supportsBelow('5.4') === false) {
  55. return;
  56. }
  57. $tokens = $phpcsFile->getTokens();
  58. if (strtolower($tokens[$stackPtr]['content']) !== 'class') {
  59. return;
  60. }
  61. $prevToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($stackPtr - 1), null, true, null, true);
  62. if ($prevToken === false || $tokens[$prevToken]['code'] !== \T_DOUBLE_COLON) {
  63. return;
  64. }
  65. $phpcsFile->addError(
  66. 'The magic class constant ClassName::class was not available in PHP 5.4 or earlier',
  67. $stackPtr,
  68. 'Found'
  69. );
  70. }
  71. }