From 6aaa87f14387c861199d2e2336e2ef200edbc7c7 Mon Sep 17 00:00:00 2001 From: Nikita Popov Date: Fri, 3 Apr 2015 22:22:39 +0200 Subject: [PATCH] Fix PHP 7 alias registration This fixes the case where the old name is used before the new one is ever used, e.g. when manually constructing nodes, as opposed to parsing them. The previous approach would try to register the alias from OLD to NEW. This would trigger autoloading on NEW and afterwards it would register the alias from OLD to NEW. Afterwards the alias registration which originally triggered the autoload would run, thus redeclaring the class. TL;DR aliases suck, closes #192. --- lib/PhpParser/Autoloader.php | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/lib/PhpParser/Autoloader.php b/lib/PhpParser/Autoloader.php index ecad0e8..1f4c656 100644 --- a/lib/PhpParser/Autoloader.php +++ b/lib/PhpParser/Autoloader.php @@ -36,10 +36,19 @@ class Autoloader static public function autoload($class) { if (0 === strpos($class, 'PhpParser\\')) { if (isset(self::$php7AliasesOldToNew[$class])) { - // Old class name was used, register alias to new one (which will - // be autoloaded, if it wasn't yet). - self::registerPhp7Alias(self::$php7AliasesOldToNew[$class], $class); - return; + if (self::$runningOnPhp7) { + return; + } + + $newClass = self::$php7AliasesOldToNew[$class]; + if (class_exists($newClass, false)) { + // If the new class is already loaded, alias it right away + class_alias($class, $newClass); + return; + } + + // Otherwise load the new class and create the alias afterwards + $class = $newClass; } $fileName = dirname(__DIR__) . '/' . strtr($class, '\\', '/') . '.php'; @@ -50,7 +59,9 @@ class Autoloader if (isset(self::$php7AliasesNewToOld[$class])) { // New class name was used, register alias for old one, otherwise // it won't be usable in "instanceof" and other non-autoloading places. - self::registerPhp7Alias($class, self::$php7AliasesNewToOld[$class]); + if (!self::$runningOnPhp7) { + class_alias($class, self::$php7AliasesNewToOld[$class]); + } } } else if (0 === strpos($class, 'PHPParser_')) { if (isset(self::$nonNamespacedAliases[$class])) { @@ -60,14 +71,6 @@ class Autoloader } } - private static function registerPhp7Alias($old, $new) { - // Registering these aliases would throw a fatal error on PHP 7, - // we want to avoid that. - if (!self::$runningOnPhp7) { - class_alias($old, $new); - } - } - private static function registerNonNamespacedAliases() { foreach (self::$nonNamespacedAliases as $old => $new) { class_alias($new, $old);