ForbiddenToStringParametersSniff.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. * As of PHP 5.3, the __toString() magic method can no longer accept arguments.
  16. *
  17. * Sister-sniff to `PHPCompatibility.MethodUse.ForbiddenToStringParameters`.
  18. *
  19. * PHP version 5.3
  20. *
  21. * @link https://www.php.net/manual/en/migration53.incompatible.php
  22. * @link https://www.php.net/manual/en/language.oop5.magic.php#object.tostring
  23. *
  24. * @since 9.2.0
  25. */
  26. class ForbiddenToStringParametersSniff extends Sniff
  27. {
  28. /**
  29. * Valid scopes for the __toString() method to live in.
  30. *
  31. * @since 9.2.0
  32. * @since 9.3.2 Visibility changed from `public` to `protected`.
  33. *
  34. * @var array
  35. */
  36. protected $ooScopeTokens = array(
  37. 'T_CLASS' => true,
  38. 'T_INTERFACE' => true,
  39. 'T_TRAIT' => true,
  40. 'T_ANON_CLASS' => true,
  41. );
  42. /**
  43. * Returns an array of tokens this test wants to listen for.
  44. *
  45. * @since 9.2.0
  46. *
  47. * @return array
  48. */
  49. public function register()
  50. {
  51. return array(\T_FUNCTION);
  52. }
  53. /**
  54. * Processes this test, when one of its tokens is encountered.
  55. *
  56. * @since 9.2.0
  57. *
  58. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  59. * @param int $stackPtr The position of the current token
  60. * in the stack passed in $tokens.
  61. *
  62. * @return void
  63. */
  64. public function process(File $phpcsFile, $stackPtr)
  65. {
  66. if ($this->supportsAbove('5.3') === false) {
  67. return;
  68. }
  69. $functionName = $phpcsFile->getDeclarationName($stackPtr);
  70. if (strtolower($functionName) !== '__tostring') {
  71. // Not the right function.
  72. return;
  73. }
  74. if ($this->validDirectScope($phpcsFile, $stackPtr, $this->ooScopeTokens) === false) {
  75. // Function, not method.
  76. return;
  77. }
  78. $params = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr);
  79. if (empty($params)) {
  80. // Function declared without parameters.
  81. return;
  82. }
  83. $phpcsFile->addError(
  84. 'The __toString() magic method can no longer accept arguments since PHP 5.3',
  85. $stackPtr,
  86. 'Declared'
  87. );
  88. }
  89. }