ForbiddenParametersWithSameNameSniff.php 2.4 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\FunctionDeclarations;
  11. use PHPCompatibility\Sniff;
  12. use PHPCompatibility\PHPCSHelper;
  13. use PHP_CodeSniffer_File as File;
  14. /**
  15. * Functions can not have multiple parameters with the same name since PHP 7.0.
  16. *
  17. * PHP version 7.0
  18. *
  19. * @link https://www.php.net/manual/en/migration70.incompatible.php#migration70.incompatible.other.func-parameters
  20. *
  21. * @since 7.0.0
  22. */
  23. class ForbiddenParametersWithSameNameSniff extends Sniff
  24. {
  25. /**
  26. * Returns an array of tokens this test wants to listen for.
  27. *
  28. * @since 7.0.0
  29. * @since 7.1.3 Allows for closures.
  30. *
  31. * @return array
  32. */
  33. public function register()
  34. {
  35. return array(
  36. \T_FUNCTION,
  37. \T_CLOSURE,
  38. );
  39. }
  40. /**
  41. * Processes this test, when one of its tokens is encountered.
  42. *
  43. * @since 7.0.0
  44. *
  45. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  46. * @param int $stackPtr The position of the current token
  47. * in the stack passed in $tokens.
  48. *
  49. * @return void
  50. */
  51. public function process(File $phpcsFile, $stackPtr)
  52. {
  53. if ($this->supportsAbove('7.0') === false) {
  54. return;
  55. }
  56. $tokens = $phpcsFile->getTokens();
  57. $token = $tokens[$stackPtr];
  58. // Skip function without body.
  59. if (isset($token['scope_opener']) === false) {
  60. return;
  61. }
  62. // Get all parameters from method signature.
  63. $parameters = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr);
  64. if (empty($parameters) || \is_array($parameters) === false) {
  65. return;
  66. }
  67. $paramNames = array();
  68. foreach ($parameters as $param) {
  69. $paramNames[] = $param['name'];
  70. }
  71. if (\count($paramNames) !== \count(array_unique($paramNames))) {
  72. $phpcsFile->addError(
  73. 'Functions can not have multiple parameters with the same name since PHP 7.0',
  74. $stackPtr,
  75. 'Found'
  76. );
  77. }
  78. }
  79. }