Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ConstantUsageSniff.php
Go to the documentation of this file.
1 <?php
7 
8 use PHP_CodeSniffer\Sniffs\Sniff;
9 use PHP_CodeSniffer\Files\File;
10 
14 class ConstantUsageSniff implements Sniff
15 {
21  protected $previousLineContent = '';
22 
26  public function register()
27  {
28  return [T_OPEN_TAG];
29  }
30 
36  public function process(File $phpcsFile, $stackPtr)
37  {
38  $tokens = $phpcsFile->getTokens();
39 
40  // Make sure this is the first open tag
41  $previousOpenTag = $phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1));
42  if ($previousOpenTag !== false) {
43  return;
44  }
45 
46  $tokenCount = 0;
47  $currentLineContent = '';
48  $currentLine = 1;
49 
50  for (; $tokenCount < $phpcsFile->numTokens; $tokenCount++) {
51  if ($tokens[$tokenCount]['line'] === $currentLine) {
52  $currentLineContent .= $tokens[$tokenCount]['content'];
53  } else {
54  $this->checkIfFirstArgumentConstant($phpcsFile, ($tokenCount - 1), $currentLineContent);
55  $currentLineContent = $tokens[$tokenCount]['content'];
56  $currentLine++;
57  }
58  }
59 
60  $this->checkIfFirstArgumentConstant($phpcsFile, ($tokenCount - 1), $currentLineContent);
61  }
62 
71  private function checkIfFirstArgumentConstant(
72  File $phpcsFile,
73  $stackPtr,
74  $lineContent
75  ) {
76  $previousLineRegexp = '/(__|Phrase)\($/im';
77  $currentLineRegexp = '/(__|Phrase)\(.+\)/';
78  $currentLineMatch = preg_match($currentLineRegexp, $lineContent) !== 0;
79  $previousLineMatch = preg_match($previousLineRegexp, $this->previousLineContent) !== 0;
80  $this->previousLineContent = $lineContent;
81  $error = 'Constants are not allowed as the first argument of translation function, use string literal instead';
82  $constantRegexp = '[^\$\'"]+::[A-Z_0-9]+.*';
83  if ($currentLineMatch) {
84  $variableRegexp = "/(__|Phrase)\({$constantRegexp}\)/";
85  if (preg_match($variableRegexp, $lineContent) !== 0) {
86  $phpcsFile->addError($error, $stackPtr, 'VariableTranslation');
87  }
88  } elseif ($previousLineMatch) {
89  $variableRegexp = "/^{$constantRegexp}/";
90  if (preg_match($variableRegexp, $lineContent) !== 0) {
91  $phpcsFile->addError($error, $stackPtr, 'VariableTranslation');
92  }
93  }
94  }
95 }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$tokens
Definition: cards_list.phtml:9