ForbiddenAbstractPrivateMethodsSniff.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. /**
  14. * Abstract private methods are not allowed since PHP 5.1.
  15. *
  16. * Abstract private methods were supported between PHP 5.0.0 and PHP 5.0.4, but
  17. * were then disallowed on the grounds that the behaviours of `private` and `abstract`
  18. * are mutually exclusive.
  19. *
  20. * PHP version 5.1
  21. *
  22. * @link https://www.php.net/manual/en/migration51.oop.php#migration51.oop-methods
  23. *
  24. * @since 9.2.0
  25. */
  26. class ForbiddenAbstractPrivateMethodsSniff extends Sniff
  27. {
  28. /**
  29. * Valid scopes to check for abstract private methods.
  30. *
  31. * @since 9.2.0
  32. *
  33. * @var array
  34. */
  35. public $ooScopeTokens = array(
  36. 'T_CLASS' => true,
  37. 'T_TRAIT' => true,
  38. 'T_ANON_CLASS' => true,
  39. );
  40. /**
  41. * Returns an array of tokens this test wants to listen for.
  42. *
  43. * @since 9.2.0
  44. *
  45. * @return array
  46. */
  47. public function register()
  48. {
  49. return array(\T_FUNCTION);
  50. }
  51. /**
  52. * Processes this test, when one of its tokens is encountered.
  53. *
  54. * @since 9.2.0
  55. *
  56. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  57. * @param int $stackPtr The position of the current token
  58. * in the stack passed in $tokens.
  59. *
  60. * @return void
  61. */
  62. public function process(File $phpcsFile, $stackPtr)
  63. {
  64. if ($this->supportsAbove('5.1') === false) {
  65. return;
  66. }
  67. if ($this->validDirectScope($phpcsFile, $stackPtr, $this->ooScopeTokens) === false) {
  68. // Function, not method.
  69. return;
  70. }
  71. $properties = $phpcsFile->getMethodProperties($stackPtr);
  72. if ($properties['scope'] !== 'private' || $properties['is_abstract'] !== true) {
  73. return;
  74. }
  75. $phpcsFile->addError(
  76. 'Abstract methods cannot be declared as private since PHP 5.1',
  77. $stackPtr,
  78. 'Found'
  79. );
  80. }
  81. }