NewAnonymousClassesSniff.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. * Anonymous classes are supported since PHP 7.0.
  16. *
  17. * PHP version 7.0
  18. *
  19. * @link https://www.php.net/manual/en/language.oop5.anonymous.php
  20. * @link https://wiki.php.net/rfc/anonymous_classes
  21. *
  22. * @since 7.0.0
  23. */
  24. class NewAnonymousClassesSniff extends Sniff
  25. {
  26. /**
  27. * Tokens which in various PHP versions indicate the `class` keyword.
  28. *
  29. * The dedicated anonymous class token is added from the `register()`
  30. * method if the token is available.
  31. *
  32. * @since 7.1.2
  33. *
  34. * @var array
  35. */
  36. private $indicators = array(
  37. \T_CLASS => \T_CLASS,
  38. );
  39. /**
  40. * Returns an array of tokens this test wants to listen for.
  41. *
  42. * @since 7.0.0
  43. *
  44. * @return array
  45. */
  46. public function register()
  47. {
  48. if (\defined('T_ANON_CLASS')) {
  49. $this->indicators[\T_ANON_CLASS] = \T_ANON_CLASS;
  50. }
  51. return array(\T_NEW);
  52. }
  53. /**
  54. * Processes this test, when one of its tokens is encountered.
  55. *
  56. * @since 7.0.0
  57. *
  58. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  59. * @param int $stackPtr The position of the current token in the
  60. * stack passed in $tokens.
  61. *
  62. * @return void
  63. */
  64. public function process(File $phpcsFile, $stackPtr)
  65. {
  66. if ($this->supportsBelow('5.6') === false) {
  67. return;
  68. }
  69. $tokens = $phpcsFile->getTokens();
  70. $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
  71. if ($nextNonEmpty === false || isset($this->indicators[$tokens[$nextNonEmpty]['code']]) === false) {
  72. return;
  73. }
  74. // Still here ? In that case, it is an anonymous class.
  75. $phpcsFile->addError(
  76. 'Anonymous classes are not supported in PHP 5.6 or earlier',
  77. $stackPtr,
  78. 'Found'
  79. );
  80. }
  81. }