NewMultiCatchSniff.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. * Catching multiple exception types in one statement is available since PHP 7.1.
  15. *
  16. * PHP version 7.1
  17. *
  18. * @link https://www.php.net/manual/en/migration71.new-features.php#migration71.new-features.mulit-catch-exception-handling
  19. * @link https://wiki.php.net/rfc/multiple-catch
  20. * @link https://www.php.net/manual/en/language.exceptions.php#language.exceptions.catch
  21. *
  22. * @since 7.0.7
  23. */
  24. class NewMultiCatchSniff extends Sniff
  25. {
  26. /**
  27. * Returns an array of tokens this test wants to listen for.
  28. *
  29. * @since 7.0.7
  30. *
  31. * @return array
  32. */
  33. public function register()
  34. {
  35. return array(\T_CATCH);
  36. }
  37. /**
  38. * Processes this test, when one of its tokens is encountered.
  39. *
  40. * @since 7.0.7
  41. *
  42. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  43. * @param int $stackPtr The position of the current token
  44. * in the stack passed in $tokens.
  45. *
  46. * @return void
  47. */
  48. public function process(File $phpcsFile, $stackPtr)
  49. {
  50. if ($this->supportsBelow('7.0') === false) {
  51. return;
  52. }
  53. $tokens = $phpcsFile->getTokens();
  54. $token = $tokens[$stackPtr];
  55. // Bow out during live coding.
  56. if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === false) {
  57. return;
  58. }
  59. $hasBitwiseOr = $phpcsFile->findNext(\T_BITWISE_OR, $token['parenthesis_opener'], $token['parenthesis_closer']);
  60. if ($hasBitwiseOr === false) {
  61. return;
  62. }
  63. $phpcsFile->addError(
  64. 'Catching multiple exceptions within one statement is not supported in PHP 7.0 or earlier.',
  65. $hasBitwiseOr,
  66. 'Found'
  67. );
  68. }
  69. }