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;
17 * @author Gyula Sallai <salla016@gmail.com>
19 class ClassMapGenerator
22 * Generate a class map file.
24 * @param array|string $dirs Directories or a single path to search in
25 * @param string $file The name of the class map file
27 public static function dump($dirs, $file)
29 $dirs = (array) $dirs;
32 foreach ($dirs as $dir) {
33 $maps = array_merge($maps, static::createMap($dir));
36 file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true)));
40 * Iterate over all files in the given directory searching for classes.
42 * @param \Iterator|string $dir The directory to search in or an iterator
44 * @return array A class map array
46 public static function createMap($dir)
48 if (is_string($dir)) {
49 $dir = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir));
54 foreach ($dir as $file) {
55 if (!$file->isFile()) {
59 $path = $file->getRealPath() ?: $file->getPathname();
61 if (pathinfo($path, PATHINFO_EXTENSION) !== 'php') {
65 $classes = self::findClasses($path);
67 if (\PHP_VERSION_ID >= 70000) {
68 // PHP 7 memory manager will not release after token_get_all(), see https://bugs.php.net/70098
72 foreach ($classes as $class) {
81 * Extract the classes in the given file.
83 * @param string $path The file to check
85 * @return array The found classes
87 private static function findClasses($path)
89 $contents = file_get_contents($path);
90 $tokens = token_get_all($contents);
95 for ($i = 0; isset($tokens[$i]); ++$i) {
98 if (!isset($token[1])) {
107 // If there is a namespace, extract it
108 while (isset($tokens[++$i][1])) {
109 if (in_array($tokens[$i][0], array(T_STRING, T_NS_SEPARATOR))) {
110 $namespace .= $tokens[$i][1];
118 // Skip usage of ::class constant
119 $isClassConstant = false;
120 for ($j = $i - 1; $j > 0; --$j) {
121 if (!isset($tokens[$j][1])) {
125 if (T_DOUBLE_COLON === $tokens[$j][0]) {
126 $isClassConstant = true;
128 } elseif (!in_array($tokens[$j][0], array(T_WHITESPACE, T_DOC_COMMENT, T_COMMENT))) {
133 if ($isClassConstant) {
137 // Find the classname
138 while (isset($tokens[++$i][1])) {
140 if (T_STRING === $t[0]) {
142 } elseif ('' !== $class && T_WHITESPACE === $t[0]) {
147 $classes[] = ltrim($namespace.$class, '\\');