diff --git a/src/Fixer/LanguageConstruct/ClassKeywordFixer.php b/src/Fixer/LanguageConstruct/ClassKeywordFixer.php new file mode 100644 index 00000000000..a227f2efd9f --- /dev/null +++ b/src/Fixer/LanguageConstruct/ClassKeywordFixer.php @@ -0,0 +1,96 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Indicator\ClassyExistanceIndicator; + +/** + * @author Dariusz Rumiński + */ +final class ClassKeywordFixer extends AbstractFixer +{ + /** + * @var string[] + */ + private $imports = array(); + + /** + * {@inheritdoc} + */ + public function getDefinition() + { + return new FixerDefinition( + 'Converts FQCN strings to `*::class` keywords. Requires PHP >= 5.5.', + array( + new VersionSpecificCodeSample( + '= 50500; + } + + /** + * {@inheritdoc} + */ + protected function applyFix(\SplFileInfo $file, Tokens $tokens) + { + $indicator = new ClassyExistanceIndicator(); + + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + + if ($token->isGivenKind(T_CONSTANT_ENCAPSED_STRING)) { + $name = substr($token->getContent(), 1, -1); + $name = ltrim($name, '\\'); + $name = str_replace('\\\\', '\\', $name); + + if ($indicator->exists($name)) { + try { + $substitution = Tokens::fromCode("clearRange(0, 2); + $substitution[$substitution->getSize() - 1]->clear(); + $substitution->clearEmptyTokens(); + + $token->clear(); + $tokens->insertAt($index, $substitution); + } catch (\Error $e) { + var_dump("error with parsing class", $name); + var_dump($e->getMessage()); + } + } + } + } + } +} diff --git a/src/Indicator/ClassyExistanceIndicator.php b/src/Indicator/ClassyExistanceIndicator.php new file mode 100644 index 00000000000..863049b5f4c --- /dev/null +++ b/src/Indicator/ClassyExistanceIndicator.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ + +namespace PhpCsFixer\Indicator; + +/** + * @internal + */ +final class ClassyExistanceIndicator +{ + /** + * @param string $name + * + * @return bool + */ + public function exists($name) + { + if (class_exists($name) || interface_exists($name) || trait_exists($name)) { + $rc = new \ReflectionClass($name); + + return $rc->getName() === $name; + } + + return false; + } +}