From: Vincent Vanwaelscappel Date: Fri, 31 May 2019 18:29:53 +0000 (+0200) Subject: #2810 X-Git-Url: http://git.cubedesigners.com/?a=commitdiff_plain;h=a11cfe8b2003570919f926ad33516e82361b2506;p=cubist_util.git #2810 --- diff --git a/src/Cubist/Util/PHP.php b/src/Cubist/Util/PHP.php index 8dda805..fffb548 100644 --- a/src/Cubist/Util/PHP.php +++ b/src/Cubist/Util/PHP.php @@ -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(); }