4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\ClassLoader;
14 if (!defined('SYMFONY_TRAIT')) {
15 if (\PHP_VERSION_ID >= 50400) {
16 define('SYMFONY_TRAIT', T_TRAIT);
18 define('SYMFONY_TRAIT', 0);
25 * @author Gyula Sallai <salla016@gmail.com>
27 class ClassMapGenerator
30 * Generate a class map file.
32 * @param array|string $dirs Directories or a single path to search in
33 * @param string $file The name of the class map file
35 public static function dump($dirs, $file)
37 $dirs = (array) $dirs;
40 foreach ($dirs as $dir) {
41 $maps = array_merge($maps, static::createMap($dir));
44 file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true)));
48 * Iterate over all files in the given directory searching for classes.
50 * @param \Iterator|string $dir The directory to search in or an iterator
52 * @return array A class map array
54 public static function createMap($dir)
56 if (is_string($dir)) {
57 $dir = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir));
62 foreach ($dir as $file) {
63 if (!$file->isFile()) {
67 $path = $file->getRealPath() ?: $file->getPathname();
69 if (pathinfo($path, PATHINFO_EXTENSION) !== 'php') {
73 $classes = self::findClasses($path);
75 if (\PHP_VERSION_ID >= 70000) {
76 // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
80 foreach ($classes as $class) {
89 * Extract the classes in the given file.
91 * @param string $path The file to check
93 * @return array The found classes
95 private static function findClasses($path)
97 $contents = file_get_contents($path);
98 $tokens = token_get_all($contents);
103 for ($i = 0; isset($tokens[$i]); ++$i) {
104 $token = $tokens[$i];
106 if (!isset($token[1])) {
115 // If there is a namespace, extract it
116 while (isset($tokens[++$i][1])) {
117 if (in_array($tokens[$i][0], array(T_STRING, T_NS_SEPARATOR))) {
118 $namespace .= $tokens[$i][1];
126 // Skip usage of ::class constant
127 $isClassConstant = false;
128 for ($j = $i - 1; $j > 0; --$j) {
129 if (!isset($tokens[$j][1])) {
133 if (T_DOUBLE_COLON === $tokens[$j][0]) {
134 $isClassConstant = true;
136 } elseif (!in_array($tokens[$j][0], array(T_WHITESPACE, T_DOC_COMMENT, T_COMMENT))) {
141 if ($isClassConstant) {
145 // Find the classname
146 while (isset($tokens[++$i][1])) {
148 if (T_STRING === $t[0]) {
150 } elseif ('' !== $class && T_WHITESPACE === $t[0]) {
155 $classes[] = ltrim($namespace.$class, '\\');