NewEmptyNonVariableSniff.php 2.6 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\LanguageConstructs;
  11. use PHPCompatibility\Sniff;
  12. use PHP_CodeSniffer_File as File;
  13. use PHP_CodeSniffer_Tokens as Tokens;
  14. /**
  15. * Verify that nothing but variables are passed to empty().
  16. *
  17. * Prior to PHP 5.5, `empty()` only supported variables; anything else resulted in a parse error.
  18. *
  19. * PHP version 5.5
  20. *
  21. * @link https://wiki.php.net/rfc/empty_isset_exprs
  22. * @link https://www.php.net/manual/en/function.empty.php
  23. *
  24. * @since 7.0.4
  25. * @since 9.0.0 The "is the parameter a variable" determination has been abstracted out
  26. * and moved to a separate method `Sniff::isVariable()`.
  27. * @since 9.0.0 Renamed from `EmptyNonVariableSniff` to `NewEmptyNonVariableSniff`.
  28. */
  29. class NewEmptyNonVariableSniff extends Sniff
  30. {
  31. /**
  32. * Returns an array of tokens this test wants to listen for.
  33. *
  34. * @since 7.0.4
  35. *
  36. * @return array
  37. */
  38. public function register()
  39. {
  40. return array(\T_EMPTY);
  41. }
  42. /**
  43. * Processes this test, when one of its tokens is encountered.
  44. *
  45. * @since 7.0.4
  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. if ($this->supportsBelow('5.4') === false) {
  56. return;
  57. }
  58. $tokens = $phpcsFile->getTokens();
  59. $open = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
  60. if ($open === false
  61. || $tokens[$open]['code'] !== \T_OPEN_PARENTHESIS
  62. || isset($tokens[$open]['parenthesis_closer']) === false
  63. ) {
  64. return;
  65. }
  66. $close = $tokens[$open]['parenthesis_closer'];
  67. $nestingLevel = 0;
  68. if ($close !== ($open + 1) && isset($tokens[$open + 1]['nested_parenthesis'])) {
  69. $nestingLevel = \count($tokens[$open + 1]['nested_parenthesis']);
  70. }
  71. if ($this->isVariable($phpcsFile, ($open + 1), $close, $nestingLevel) === true) {
  72. return;
  73. }
  74. $phpcsFile->addError(
  75. 'Only variables can be passed to empty() prior to PHP 5.5.',
  76. $stackPtr,
  77. 'Found'
  78. );
  79. }
  80. }