Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
StringPositionSniff.php
Go to the documentation of this file.
1 <?php
7 
8 use PHP_CodeSniffer\Sniffs\Sniff;
9 use PHP_CodeSniffer\Files\File;
10 
18 class StringPositionSniff implements Sniff
19 {
25  protected $errorMessage = 'Identical operator === is not used for testing the return value of %s function';
26 
32  protected $errorCode = 'ImproperValueTesting';
33 
39  protected $functions = [
40  'strpos',
41  'stripos',
42  ];
43 
49  protected $tokens = [];
50 
56  protected $file;
57 
63  protected $leftLimit;
64 
70  protected $rightLimit;
71 
77  protected $leftRangeTokens = [
78  T_IS_IDENTICAL,
79  T_IS_NOT_IDENTICAL,
80  T_OPEN_PARENTHESIS,
81  T_BOOLEAN_AND,
82  T_BOOLEAN_OR,
83  ];
84 
90  protected $rightRangeTokens = [
91  T_IS_IDENTICAL,
92  T_IS_NOT_IDENTICAL,
93  T_CLOSE_PARENTHESIS,
94  T_BOOLEAN_AND,
95  T_BOOLEAN_OR,
96  ];
97 
103  protected $identical = [
104  T_IS_IDENTICAL,
105  T_IS_NOT_IDENTICAL,
106  ];
107 
111  public function register()
112  {
113  return [T_IF, T_ELSEIF];
114  }
115 
119  public function process(File $phpcsFile, $stackPtr)
120  {
121  $this->tokens = $phpcsFile->getTokens();
122  $this->file = $phpcsFile;
123  $this->leftLimit = $open = $this->tokens[$stackPtr]['parenthesis_opener'];
124  $this->rightLimit = $close = $this->tokens[$stackPtr]['parenthesis_closer'];
125  for ($i = ($open + 1); $i < $close; $i++) {
126  if (($this->tokens[$i]['code'] === T_STRING && in_array($this->tokens[$i]['content'], $this->functions))
127  && (!$this->findIdentical($i - 1, $this->findFunctionParenthesisCloser($i) + 1))
128  ) {
129  $foundFunctionName = $this->tokens[$i]['content'];
130  $phpcsFile->addError($this->errorMessage, $i, $this->errorCode, [$foundFunctionName]);
131  }
132  }
133  }
134 
142  protected function findIdentical($leftCurrentPosition, $rightCurrentPosition)
143  {
144  $leftBound = $this->file->findPrevious($this->leftRangeTokens, $leftCurrentPosition, $this->leftLimit - 1);
145  $rightBound = $this->file->findNext($this->rightRangeTokens, $rightCurrentPosition, $this->rightLimit + 1);
146  $leftToken = $this->tokens[$leftBound];
147  $rightToken = $this->tokens[$rightBound];
148  if ($leftToken['code'] === T_OPEN_PARENTHESIS && $rightToken['code'] === T_CLOSE_PARENTHESIS) {
149  return $this->findIdentical($leftBound - 1, $rightBound + 1);
150  } else {
151  return (
152  in_array($leftToken['code'], $this->identical) || in_array($rightToken['code'], $this->identical)
153  ) ?: false;
154  }
155  }
156 
163  protected function findFunctionParenthesisCloser($currentPosition)
164  {
165  $nextOpenParenthesis = $this->file->findNext(T_OPEN_PARENTHESIS, $currentPosition, $this->rightLimit);
166  return $nextOpenParenthesis ? $this->tokens[$nextOpenParenthesis]['parenthesis_closer'] : false;
167  }
168 }
findIdentical($leftCurrentPosition, $rightCurrentPosition)
$i
Definition: gallery.phtml:31