NewLateStaticBindingSniff.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. * Detect use of late static binding as introduced in PHP 5.3.
  16. *
  17. * Checks for:
  18. * - Late static binding as introduced in PHP 5.3.
  19. * - Late static binding being used outside of class scope (unsupported).
  20. *
  21. * PHP version 5.3
  22. *
  23. * @link https://www.php.net/manual/en/language.oop5.late-static-bindings.php
  24. * @link https://wiki.php.net/rfc/lsb_parentself_forwarding
  25. *
  26. * @since 7.0.3
  27. * @since 9.0.0 Renamed from `LateStaticBindingSniff` to `NewLateStaticBindingSniff`.
  28. */
  29. class NewLateStaticBindingSniff extends Sniff
  30. {
  31. /**
  32. * Returns an array of tokens this test wants to listen for.
  33. *
  34. * @since 7.0.3
  35. *
  36. * @return array
  37. */
  38. public function register()
  39. {
  40. return array(\T_STATIC);
  41. }
  42. /**
  43. * Processes this test, when one of its tokens is encountered.
  44. *
  45. * @since 7.0.3
  46. *
  47. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  48. * @param int $stackPtr The position of the current token in the
  49. * stack passed in $tokens.
  50. *
  51. * @return void
  52. */
  53. public function process(File $phpcsFile, $stackPtr)
  54. {
  55. $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
  56. if ($nextNonEmpty === false) {
  57. return;
  58. }
  59. $tokens = $phpcsFile->getTokens();
  60. if ($tokens[$nextNonEmpty]['code'] !== \T_DOUBLE_COLON) {
  61. return;
  62. }
  63. $inClass = $this->inClassScope($phpcsFile, $stackPtr, false);
  64. if ($inClass === true && $this->supportsBelow('5.2') === true) {
  65. $phpcsFile->addError(
  66. 'Late static binding is not supported in PHP 5.2 or earlier.',
  67. $stackPtr,
  68. 'Found'
  69. );
  70. }
  71. if ($inClass === false) {
  72. $phpcsFile->addError(
  73. 'Late static binding is not supported outside of class scope.',
  74. $stackPtr,
  75. 'OutsideClassScope'
  76. );
  77. }
  78. }
  79. }