TokenizerLinter.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Linter;
  13. use PhpCsFixer\FileReader;
  14. use PhpCsFixer\Tokenizer\CodeHasher;
  15. use PhpCsFixer\Tokenizer\Tokens;
  16. /**
  17. * Handle PHP code linting.
  18. *
  19. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  20. *
  21. * @internal
  22. */
  23. final class TokenizerLinter implements LinterInterface
  24. {
  25. public function isAsync(): bool
  26. {
  27. return false;
  28. }
  29. public function lintFile(string $path): LintingResultInterface
  30. {
  31. return $this->lintSource(FileReader::createSingleton()->read($path));
  32. }
  33. public function lintSource(string $source): LintingResultInterface
  34. {
  35. try {
  36. // To lint, we will parse the source into Tokens.
  37. // During that process, it might throw a ParseError or CompileError.
  38. // If it won't, cache of tokenized version of source will be kept, which is great for Runner.
  39. // Yet, first we need to clear already existing cache to not hit it and lint the code indeed.
  40. $codeHash = CodeHasher::calculateCodeHash($source);
  41. Tokens::clearCache($codeHash);
  42. Tokens::fromCode($source);
  43. return new TokenizerLintingResult();
  44. } catch (\CompileError|\ParseError $e) {
  45. return new TokenizerLintingResult($e);
  46. }
  47. }
  48. }