From a041ff1328be4f8a7fba4f1e7fdb0d5d50fd25a4 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Wed, 17 Mar 2021 06:01:09 +0100 Subject: [PATCH] SniffParser: add slash normalization Fixes #4 Includes tests. --- src/Parser/SniffParser.php | 13 +++++++++ tests/Parser/SniffParserTest.php | 48 ++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/src/Parser/SniffParser.php b/src/Parser/SniffParser.php index d8e4565..738f306 100644 --- a/src/Parser/SniffParser.php +++ b/src/Parser/SniffParser.php @@ -27,6 +27,7 @@ class SniffParser { public function parse(string $phpFilePath, SourceLocator $projectSourceLocator): Sniff { + $phpFilePath = $this->normalizeSlashes($phpFilePath); $astLocator = (new BetterReflection())->astLocator(); $reflector = new ClassReflector( new AggregateSourceLocator([ @@ -211,4 +212,16 @@ private function getUrls(ReflectionClass $classInfo, array $xmlUrls): UrlList return new UrlList(array_merge($urls, $xmlUrls)); } + + /** + * Normalizes all slashes in a file path to forward slashes. + * + * @param string $path File path. + * + * @return string The file path with normalized slashes. + */ + private function normalizeSlashes($path) + { + return str_replace('\\', '/', $path); + } } diff --git a/tests/Parser/SniffParserTest.php b/tests/Parser/SniffParserTest.php index a53403b..aac916a 100644 --- a/tests/Parser/SniffParserTest.php +++ b/tests/Parser/SniffParserTest.php @@ -19,6 +19,7 @@ class SniffParserTest extends TestCase { private const PHP_FILE_PATH = 'var/tests/src/Standard/Sniffs/Category/MySniff.php'; private const XML_FILE_PATH = 'var/tests/src/Standard/Docs/Category/MyStandard.xml'; + private const PHP_FILE_PATH_MIXED_SLASHES = 'var\tests\src\Standard/Sniffs/Category\MySniff.php'; private SniffParser $parser; private Locator $astLocator; @@ -246,6 +247,53 @@ class MySniff {} ); } + /** @test */ + public function parse_WithWindowsSlashesInPhpPath() + { + $content = 'dumpFile(self::PHP_FILE_PATH, $content); + $doc = $this->parser->parse(str_replace('/', '\\', self::PHP_FILE_PATH), new StringSourceLocator($content, $this->astLocator)); + self::assertEquals( + 'Standard.Category.My', + $doc->getCode() + ); + } + + /** @test */ + public function parse_WithMixedSlashesInPhpPath() + { + $content = 'dumpFile(self::PHP_FILE_PATH, $content); + + $doc = $this->parser->parse(self::PHP_FILE_PATH_MIXED_SLASHES, new StringSourceLocator($content, $this->astLocator)); + self::assertEquals( + 'Standard.Category.My', + $doc->getCode() + ); + } + /** @test */ public function parse_WithInvalidPhpPath_ThrowException() {