Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
LiteralNamespacesSniff.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 LiteralNamespacesSniff implements Sniff
15 {
19  private $literalNamespacePattern = '/^[\\\]{0,2}[A-Z][A-Za-z]+([\\\]{1,2}[A-Z][A-Za-z]+){2,}(?!\\\+)$/';
20 
24  private $classNames = [];
25 
29  public function register()
30  {
31  return [
32  T_CONSTANT_ENCAPSED_STRING,
33  T_DOUBLE_QUOTED_STRING,
34  ];
35  }
36 
40  public function process(File $sourceFile, $stackPtr)
41  {
42  $tokens = $sourceFile->getTokens();
43  if ($sourceFile->findPrevious(T_STRING_CONCAT, $stackPtr, $stackPtr - 3) ||
44  $sourceFile->findNext(T_STRING_CONCAT, $stackPtr, $stackPtr + 3)
45  ) {
46  return;
47  }
48 
49  $content = trim($tokens[$stackPtr]['content'], "\"'");
50  // replace double slashes from class name for avoiding problems with class autoload
51  if (strpos($content, '\\') !== false) {
52  $content = preg_replace('|\\\{2,}|', '\\', $content);
53  }
54 
55  if (preg_match($this->literalNamespacePattern, $content) === 1 && $this->classExists($content)) {
56  $sourceFile->addError(
57  "Use ::class notation instead.",
58  $stackPtr,
59  'LiteralClassUsage'
60  );
61  }
62  }
63 
68  private function classExists($className)
69  {
70  if (!isset($this->classNames[$className])) {
71  $this->classNames[$className] = class_exists($className) || interface_exists($className);
72  }
73  return $this->classNames[$className];
74  }
75 }
$tokens
Definition: cards_list.phtml:9
if($currentSelectedMethod==$_code) $className
Definition: form.phtml:31