PageRenderTime 37ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/dev/tests/static/framework/Magento/Sniffs/LiteralNamespaces/LiteralNamespacesSniff.php

https://gitlab.com/crazybutterfly815/magento2
PHP | 66 lines | 41 code | 6 blank | 19 comment | 1 complexity | fec726d2a6bdbceb9f68e209fa048a6c MD5 | raw file
  1. <?php
  2. /**
  3. * Copyright © 2016 Magento. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Sniffs\LiteralNamespaces;
  7. use PHP_CodeSniffer_File;
  8. use PHP_CodeSniffer_Sniff;
  9. /**
  10. * Custom phpcs sniff to detect usages of literal class and interface names.
  11. */
  12. class LiteralNamespacesSniff implements PHP_CodeSniffer_Sniff
  13. {
  14. /**
  15. * @var string
  16. */
  17. private $literalNamespacePattern = '/^[\\\]{0,2}[A-Z][A-Za-z]+([\\\]{1,2}[A-Z][A-Za-z]+){2,}(?!\\\+)$/';
  18. /**
  19. * @var array
  20. */
  21. private $classNames = [];
  22. /**
  23. * @inheritdoc
  24. */
  25. public function register()
  26. {
  27. return [
  28. T_CONSTANT_ENCAPSED_STRING,
  29. T_DOUBLE_QUOTED_STRING,
  30. ];
  31. }
  32. /**
  33. * @inheritdoc
  34. */
  35. public function process(PHP_CodeSniffer_File $sourceFile, $stackPtr)
  36. {
  37. $tokens = $sourceFile->getTokens();
  38. if ($sourceFile->findPrevious(T_STRING_CONCAT, $stackPtr, $stackPtr - 3) ||
  39. $sourceFile->findNext(T_STRING_CONCAT, $stackPtr, $stackPtr + 3)
  40. ) {
  41. return;
  42. }
  43. $content = trim($tokens[$stackPtr]['content'], "\"'");
  44. if (preg_match($this->literalNamespacePattern, $content) === 1 && $this->classExists($content)) {
  45. $sourceFile->addError("Use ::class notation instead.", $stackPtr);
  46. }
  47. }
  48. /**
  49. * @param string $className
  50. * @return bool
  51. */
  52. private function classExists($className)
  53. {
  54. if (!isset($this->classNames[$className])) {
  55. $this->classNames[$className] = class_exists($className) || interface_exists($className);
  56. }
  57. return $this->classNames[$className];
  58. }
  59. }