LanguageConstructsSniff.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Sniffs\LanguageConstructs;
  7. use PHP_CodeSniffer\Sniffs\Sniff;
  8. use PHP_CodeSniffer\Files\File;
  9. /**
  10. * Detects possible usage of discouraged language constructs. Is not applicable to *.phtml files.
  11. *
  12. * Examples:
  13. * echo 'echo text';
  14. * print('print text');
  15. * $string = `back quotes`;
  16. */
  17. class LanguageConstructsSniff implements Sniff
  18. {
  19. /**
  20. * String representation of error.
  21. *
  22. * @var string
  23. */
  24. protected $errorMessage = 'Use of %s language construct is discouraged.';
  25. /**
  26. * String representation of backtick error.
  27. *
  28. * @var string
  29. */
  30. // @codingStandardsIgnoreLine
  31. protected $errorMessageBacktick = 'Incorrect usage of back quote string constant. Back quotes should be always inside strings.';
  32. /**
  33. * Backtick violation code.
  34. *
  35. * @var string
  36. */
  37. protected $backtickCode = 'WrongBackQuotesUsage';
  38. /**
  39. * Direct output code.
  40. *
  41. * @var string
  42. */
  43. protected $directOutput = 'DirectOutput';
  44. /**
  45. * @inheritdoc
  46. */
  47. public function register()
  48. {
  49. return [
  50. T_ECHO,
  51. T_PRINT,
  52. T_BACKTICK,
  53. ];
  54. }
  55. /**
  56. * @inheritdoc
  57. */
  58. public function process(File $phpcsFile, $stackPtr)
  59. {
  60. $tokens = $phpcsFile->getTokens();
  61. if ($tokens[$stackPtr]['code'] === T_BACKTICK) {
  62. if ($phpcsFile->findNext(T_BACKTICK, $stackPtr + 1)) {
  63. return;
  64. }
  65. $phpcsFile->addError($this->errorMessageBacktick, $stackPtr, $this->backtickCode);
  66. return;
  67. }
  68. $phpcsFile->addError($this->errorMessage, $stackPtr, $this->directOutput, [$tokens[$stackPtr]['content']]);
  69. }
  70. }