diff --git a/packages/CodingStandard/src/Fixer/Php/ClassStringToClassConstantFixer.php b/packages/CodingStandard/src/Fixer/Php/ClassStringToClassConstantFixer.php new file mode 100644 index 00000000000..08b1681d7ac --- /dev/null +++ b/packages/CodingStandard/src/Fixer/Php/ClassStringToClassConstantFixer.php @@ -0,0 +1,88 @@ +toArray(), true) as $index => $token) { + /** @var Token $token */ + if (! $this->isStringToken($token)) { + continue; + } + + $potentialClassOrInterfaceName = trim($token->getContent(), "'"); + if (class_exists($potentialClassOrInterfaceName) || interface_exists($potentialClassOrInterfaceName)) { + $token->clear(); // overrideAt() fails on "Illegal offset type" + $tokens->insertAt($index, [ + new Token([T_NS_SEPARATOR, '\\']), + new Token([T_STRING, $potentialClassOrInterfaceName]), + new Token([T_DOUBLE_COLON, '::']), + new Token([CT::T_CLASS_CONSTANT, 'class']), + ]); + } + } + } + + public function isRisky(): bool + { + return false; + } + + public function getName(): string + { + return self::class; + } + + public function getPriority(): int + { + // @todo combine with namespace import fixer/sniff + return 0; + } + + public function supports(SplFileInfo $file): bool + { + return true; + } + + private function isStringToken(Token $token): bool + { + return Strings::startsWith($token->getContent(), "'") + && Strings::endsWith($token->getContent(), "'"); + } +} diff --git a/packages/CodingStandard/tests/Fixer/Php/ClassStringToClassConstantFixerTest.php b/packages/CodingStandard/tests/Fixer/Php/ClassStringToClassConstantFixerTest.php new file mode 100644 index 00000000000..567286422aa --- /dev/null +++ b/packages/CodingStandard/tests/Fixer/Php/ClassStringToClassConstantFixerTest.php @@ -0,0 +1,40 @@ +doTest($expected, $input); + } + + /** + * @return string[][] + */ + public function provideFixCases(): array + { + return [ + [ + file_get_contents(__DIR__ . '/fixed/fixed.php.inc'), + file_get_contents(__DIR__ . '/wrong/wrong.php.inc'), + ], + [ + file_get_contents(__DIR__ . '/fixed/fixed2.php.inc'), + file_get_contents(__DIR__ . '/wrong/wrong2.php.inc'), + ], + ]; + } + + protected function createFixer(): FixerInterface + { + return new ClassStringToClassConstantFixer; + } +} diff --git a/packages/CodingStandard/tests/Fixer/Php/fixed/fixed.php.inc b/packages/CodingStandard/tests/Fixer/Php/fixed/fixed.php.inc new file mode 100644 index 00000000000..316e0f7feb0 --- /dev/null +++ b/packages/CodingStandard/tests/Fixer/Php/fixed/fixed.php.inc @@ -0,0 +1,3 @@ +