]> _ Git - cubist_util.git/commitdiff
#2810
authorVincent Vanwaelscappel <vincent@cubedesigners.com>
Fri, 31 May 2019 18:29:53 +0000 (20:29 +0200)
committerVincent Vanwaelscappel <vincent@cubedesigners.com>
Fri, 31 May 2019 18:29:53 +0000 (20:29 +0200)
src/Cubist/Util/PHP.php

index 8dda80570ab257d1a7c2d4ae7f5f1a3b022f7b2b..fffb548577ebca2277dc5ba655c8dcd30f8f6778 100644 (file)
@@ -23,16 +23,33 @@ class PHP
      */
     public static function instanciateClassInFile($file)
     {
-        $classes = get_declared_classes();
-        include $file;
-        $diff = array_diff(get_declared_classes(), $classes);
-        $class = null;
-        foreach ($diff as $diffclass) {
-            if (realpath($file) == realpath(self::getFileDeclaring($diffclass))) {
-                $class = $diffclass;
+        $content = file_get_contents($file);
+        $tokens = token_get_all($content);
+        $namespace = '';
+        for ($index = 0; isset($tokens[$index]); $index++) {
+            if (!isset($tokens[$index][0])) {
+                continue;
+            }
+            if (T_NAMESPACE === $tokens[$index][0]) {
+                $index += 2; // Skip namespace keyword and whitespace
+                while (isset($tokens[$index]) && is_array($tokens[$index])) {
+                    $namespace .= $tokens[$index++][1];
+                }
+            }
+            if (T_CLASS === $tokens[$index][0] && T_WHITESPACE === $tokens[$index + 1][0] && T_STRING === $tokens[$index + 2][0]) {
+                $index += 2; // Skip class keyword and whitespace
+                $fqcns[] = $namespace . '\\' . $tokens[$index][1];
+
+                # break if you have one class per file (psr-4 compliant)
+                # otherwise you'll need to handle class constants (Foo::class)
                 break;
             }
         }
+        if (count($fqcns) > 0) {
+            $class = array_shift($fqcns);
+        } else {
+            return null;
+        }
         if (null !== $class) {
             return new $class();
         }