[BUGFIX] Harden fallback class map generation
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Core / ClassLoadingInformationGenerator.php
1 <?php
2 namespace TYPO3\CMS\Core\Core;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use Composer\Autoload\ClassLoader;
18 use Composer\Autoload\ClassMapGenerator;
19 use TYPO3\CMS\Core\Package\PackageInterface;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21
22 /**
23 * Generates class loading information (class maps, class aliases etc.) and writes it to files
24 * for further inclusion in the bootstrap
25 * @internal
26 */
27 class ClassLoadingInformationGenerator
28 {
29 /**
30 * @var PackageInterface[]
31 */
32 protected $activeExtensionPackages;
33
34 /**
35 * @var ClassLoader
36 */
37 protected $classLoader;
38
39 /**
40 * @var string
41 */
42 protected $installationRoot;
43
44 /**
45 * @var bool
46 */
47 protected $isDevMode;
48
49 /**
50 * @param ClassLoader $classLoader
51 * @param array $activeExtensionPackages
52 * @param string $installationRoot
53 * @param bool $isDevMode
54 */
55 public function __construct(ClassLoader $classLoader, array $activeExtensionPackages, $installationRoot, $isDevMode = false)
56 {
57 $this->classLoader = $classLoader;
58 $this->activeExtensionPackages = $activeExtensionPackages;
59 $this->installationRoot = $installationRoot;
60 $this->isDevMode = $isDevMode;
61 }
62
63 /**
64 * Returns class loading information for a single package
65 *
66 * @param PackageInterface $package The package to generate the class loading info for
67 * @param bool $useRelativePaths If set to TRUE, make the path relative to the current TYPO3 instance (PATH_site)
68 * @return array
69 */
70 public function buildClassLoadingInformationForPackage(PackageInterface $package, $useRelativePaths = false)
71 {
72 $classMap = array();
73 $psr4 = array();
74 $packagePath = $package->getPackagePath();
75 $manifest = $package->getValueFromComposerManifest();
76
77 if (empty($manifest->autoload)) {
78 // Legacy mode: Scan the complete extension directory for class files
79 $classMap = $this->createClassMap($packagePath, $useRelativePaths, !$this->isDevMode);
80 } else {
81 $autoloadPsr4 = $this->getAutoloadSectionFromManifest($manifest, 'psr-4');
82 if (!empty($autoloadPsr4)) {
83 $classLoaderPrefixesPsr4 = $this->classLoader->getPrefixesPsr4();
84 foreach ($autoloadPsr4 as $namespacePrefix => $path) {
85 $namespacePath = $packagePath . $path;
86 if ($useRelativePaths) {
87 $psr4[$namespacePrefix] = $this->makePathRelative($namespacePath, realpath($namespacePath));
88 } else {
89 $psr4[$namespacePrefix] = $namespacePath;
90 }
91 if (!empty($classLoaderPrefixesPsr4[$namespacePrefix])) {
92 // The namespace prefix has been registered already, which means there also might be
93 // a class map which we need to override
94 $classMap = array_merge($classMap, $this->createClassMap($namespacePath, $useRelativePaths, false, $namespacePrefix));
95 }
96 }
97 }
98 $autoloadClassmap = $this->getAutoloadSectionFromManifest($manifest, 'classmap');
99 if (!empty($autoloadClassmap)) {
100 foreach ($autoloadClassmap as $path) {
101 $classMap = array_merge($classMap, $this->createClassMap($packagePath . $path, $useRelativePaths));
102 }
103 }
104 }
105
106 return array('classMap' => $classMap, 'psr-4' => $psr4);
107 }
108
109 /**
110 * Fetches class loading info from the according section from the manifest file.
111 * Development information will be extracted and merged as well.
112 *
113 * @param \stdClass $manifest
114 * @param string $section
115 * @return array
116 */
117 protected function getAutoloadSectionFromManifest($manifest, $section)
118 {
119 $finalAutoloadSection = [];
120 $autoloadDefinition = json_decode(json_encode($manifest->autoload), true);
121 if (!empty($autoloadDefinition[$section]) && is_array($autoloadDefinition[$section])) {
122 $finalAutoloadSection = $autoloadDefinition[$section];
123 }
124 if ($this->isDevMode) {
125 if (isset($manifest->{'autoload-dev'})) {
126 $autoloadDefinitionDev = json_decode(json_encode($manifest->{'autoload-dev'}), true);
127 if (!empty($autoloadDefinitionDev[$section]) && is_array($autoloadDefinitionDev[$section])) {
128 $finalAutoloadSection = array_merge($finalAutoloadSection, $autoloadDefinitionDev[$section]);
129 }
130 }
131 }
132
133 return $finalAutoloadSection;
134 }
135
136 /**
137 * Creates a class map for a given (absolute) path
138 *
139 * @param string $classesPath
140 * @param bool $useRelativePaths
141 * @param bool $ignorePotentialTestClasses
142 * @param string $namespace
143 * @return array
144 */
145 protected function createClassMap($classesPath, $useRelativePaths = false, $ignorePotentialTestClasses = false, $namespace = null)
146 {
147 $classMap = array();
148 $blacklistExpression = null;
149 if ($ignorePotentialTestClasses) {
150 $blacklistPathPrefix = realpath($classesPath);
151 $blacklistExpression = "{($blacklistPathPrefix/tests/|$blacklistPathPrefix/Tests/|$blacklistPathPrefix/Resources/|$blacklistPathPrefix/res/|$blacklistPathPrefix/class.ext_update.php)}";
152 }
153 foreach (ClassMapGenerator::createMap($classesPath, $blacklistExpression, null, $namespace) as $class => $path) {
154 if ($useRelativePaths) {
155 $classMap[$class] = $this->makePathRelative($classesPath, $path);
156 } else {
157 $classMap[$class] = $path;
158 }
159 }
160 return $classMap;
161 }
162
163 /**
164 * Returns class alias map for given package
165 *
166 * @param PackageInterface $package The package to generate the class alias info for
167 * @throws \TYPO3\CMS\Core\Error\Exception
168 * @return array
169 */
170 public function buildClassAliasMapForPackage(PackageInterface $package)
171 {
172 $aliasToClassNameMapping = [];
173 $classNameToAliasMapping = [];
174 $possibleClassAliasFiles = [];
175 $manifest = $package->getValueFromComposerManifest();
176 if (!empty($manifest->extra->{'typo3/class-alias-loader'}->{'class-alias-maps'})) {
177 $possibleClassAliasFiles = $manifest->extra->{'typo3/class-alias-loader'}->{'class-alias-maps'};
178 if (!is_array($possibleClassAliasFiles)) {
179 throw new \TYPO3\CMS\Core\Error\Exception('"typo3/class-alias-loader"/"class-alias-maps" must return an array!', 1444142481);
180 }
181 } else {
182 $possibleClassAliasFiles[] = 'Migrations/Code/ClassAliasMap.php';
183 }
184 $packagePath = $package->getPackagePath();
185 foreach ($possibleClassAliasFiles as $possibleClassAliasFile) {
186 $possiblePathToClassAliasFile = $packagePath . $possibleClassAliasFile;
187 if (file_exists($possiblePathToClassAliasFile)) {
188 $packageAliasMap = require $possiblePathToClassAliasFile;
189 if (!is_array($packageAliasMap)) {
190 throw new \TYPO3\CMS\Core\Error\Exception('"class alias maps" must return an array', 1422625075);
191 }
192 foreach ($packageAliasMap as $aliasClassName => $className) {
193 $lowerCasedAliasClassName = strtolower($aliasClassName);
194 $aliasToClassNameMapping[$lowerCasedAliasClassName] = $className;
195 $classNameToAliasMapping[$className][$lowerCasedAliasClassName] = $lowerCasedAliasClassName;
196 }
197 }
198 }
199
200 return array('aliasToClassNameMapping' => $aliasToClassNameMapping, 'classNameToAliasMapping' => $classNameToAliasMapping);
201 }
202
203 /**
204 * Generate the class map file
205 * @return string[]
206 * @internal
207 */
208 public function buildAutoloadInformationFiles()
209 {
210 $psr4File = $classMapFile = <<<EOF
211 <?php
212
213 // autoload_classmap.php @generated by TYPO3
214
215 \$typo3InstallDir = PATH_site;
216
217 return array(
218
219 EOF;
220 $classMap = array();
221 $psr4 = array();
222 foreach ($this->activeExtensionPackages as $package) {
223 $classLoadingInformation = $this->buildClassLoadingInformationForPackage($package, true);
224 $classMap = array_merge($classMap, $classLoadingInformation['classMap']);
225 $psr4 = array_merge($psr4, $classLoadingInformation['psr-4']);
226 }
227
228 ksort($classMap);
229 ksort($psr4);
230 foreach ($classMap as $class => $relativePath) {
231 $classMapFile .= sprintf(' %s => %s,', var_export($class, true), $this->getPathCode($relativePath)) . LF;
232 }
233 $classMapFile .= ");\n";
234
235 foreach ($psr4 as $prefix => $relativePath) {
236 $psr4File .= sprintf(' %s => array(%s),', var_export($prefix, true), $this->getPathCode($relativePath)) . LF;
237 }
238 $psr4File .= ");\n";
239
240 return array('classMapFile' => $classMapFile, 'psr-4File' => $psr4File);
241 }
242
243 /**
244 * Generate a relative path string from an absolute path within a give package path
245 *
246 * @param string $packagePath
247 * @param string $realPathOfClassFile
248 * @param bool $relativeToRoot
249 * @return string
250 */
251 protected function makePathRelative($packagePath, $realPathOfClassFile, $relativeToRoot = true)
252 {
253 $realPathOfClassFile = GeneralUtility::fixWindowsFilePath($realPathOfClassFile);
254 $packageRealPath = GeneralUtility::fixWindowsFilePath(realpath($packagePath));
255 $relativePackagePath = rtrim(substr($packagePath, strlen($this->installationRoot)), '/');
256 if ($relativeToRoot) {
257 if ($realPathOfClassFile === $packageRealPath) {
258 $relativePathToClassFile = $relativePackagePath;
259 } else {
260 $relativePathToClassFile = $relativePackagePath . '/' . ltrim(substr($realPathOfClassFile, strlen($packageRealPath)), '/');
261 }
262 } else {
263 $relativePathToClassFile = ltrim(substr($realPathOfClassFile, strlen($packageRealPath)), '/');
264 }
265
266 return $relativePathToClassFile;
267 }
268
269 /**
270 * Generate a relative path string from a relative path
271 *
272 * @param string $relativePathToClassFile
273 * @return string
274 */
275 protected function getPathCode($relativePathToClassFile)
276 {
277 return '$typo3InstallDir . ' . var_export($relativePathToClassFile, true);
278 }
279
280 /**
281 * Build class alias mapping file
282 *
283 * @return string
284 * @throws \Exception
285 * @internal
286 */
287 public function buildClassAliasMapFile()
288 {
289 $aliasToClassNameMapping = array();
290 $classNameToAliasMapping = array();
291 foreach ($this->activeExtensionPackages as $package) {
292 $aliasMappingForPackage = $this->buildClassAliasMapForPackage($package);
293 $aliasToClassNameMapping = array_merge($aliasToClassNameMapping, $aliasMappingForPackage['aliasToClassNameMapping']);
294 $classNameToAliasMapping = array_merge($classNameToAliasMapping, $aliasMappingForPackage['classNameToAliasMapping']);
295 }
296 $exportArray = array(
297 'aliasToClassNameMapping' => $aliasToClassNameMapping,
298 'classNameToAliasMapping' => $classNameToAliasMapping
299 );
300 $fileContent = '<?php' . chr(10) . 'return ';
301 $fileContent .= var_export($exportArray, true);
302 $fileContent .= ";\n";
303 return $fileContent;
304 }
305 }