1
0
mirror of https://github.com/danog/PHP-Parser.git synced 2025-01-22 13:51:12 +01:00

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.
This commit is contained in:
Nikita Popov 2015-04-03 22:22:39 +02:00
parent 08f97eb4ef
commit 6aaa87f143

View File

@ -36,12 +36,21 @@ 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);
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';
if (file_exists($fileName)) {
require $fileName;
@ -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);