ForbiddenSwitchWithMultipleDefaultBlocksSniff.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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\ControlStructures;
  11. use PHPCompatibility\Sniff;
  12. use PHP_CodeSniffer_File as File;
  13. /**
  14. * Switch statements can not have multiple default blocks since PHP 7.0.
  15. *
  16. * PHP version 7.0
  17. *
  18. * @link https://wiki.php.net/rfc/switch.default.multiple
  19. * @link https://www.php.net/manual/en/control-structures.switch.php
  20. *
  21. * @since 7.0.0
  22. */
  23. class ForbiddenSwitchWithMultipleDefaultBlocksSniff extends Sniff
  24. {
  25. /**
  26. * Returns an array of tokens this test wants to listen for.
  27. *
  28. * @since 7.0.0
  29. *
  30. * @return array
  31. */
  32. public function register()
  33. {
  34. return array(\T_SWITCH);
  35. }
  36. /**
  37. * Processes this test, when one of its tokens is encountered.
  38. *
  39. * @since 7.0.0
  40. *
  41. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  42. * @param int $stackPtr The position of the current token
  43. * in the stack passed in $tokens.
  44. *
  45. * @return void
  46. */
  47. public function process(File $phpcsFile, $stackPtr)
  48. {
  49. if ($this->supportsAbove('7.0') === false) {
  50. return;
  51. }
  52. $tokens = $phpcsFile->getTokens();
  53. if (isset($tokens[$stackPtr]['scope_closer']) === false) {
  54. return;
  55. }
  56. $defaultToken = $stackPtr;
  57. $defaultCount = 0;
  58. $targetLevel = $tokens[$stackPtr]['level'] + 1;
  59. while ($defaultCount < 2 && ($defaultToken = $phpcsFile->findNext(array(\T_DEFAULT), $defaultToken + 1, $tokens[$stackPtr]['scope_closer'])) !== false) {
  60. // Same level or one below (= two default cases after each other).
  61. if ($tokens[$defaultToken]['level'] === $targetLevel || $tokens[$defaultToken]['level'] === ($targetLevel + 1)) {
  62. $defaultCount++;
  63. }
  64. }
  65. if ($defaultCount > 1) {
  66. $phpcsFile->addError(
  67. 'Switch statements can not have multiple default blocks since PHP 7.0',
  68. $stackPtr,
  69. 'Found'
  70. );
  71. }
  72. }
  73. }