Move ClassCollector to its own file
[lhc/web/wiklou.git] / includes / utils / AutoloadGenerator.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 /**
22 * Accepts a list of files and directories to search for
23 * php files and generates $wgAutoloadLocalClasses or $wgAutoloadClasses
24 * lines for all detected classes. These lines are written out
25 * to an autoload.php file in the projects provided basedir.
26 *
27 * Usage:
28 *
29 * $gen = new AutoloadGenerator( __DIR__ );
30 * $gen->readDir( __DIR__ . '/includes' );
31 * $gen->readFile( __DIR__ . '/foo.php' )
32 * $gen->getAutoload();
33 */
34 class AutoloadGenerator {
35 const FILETYPE_JSON = 'json';
36 const FILETYPE_PHP = 'php';
37
38 /**
39 * @var string Root path of the project being scanned for classes
40 */
41 protected $basepath;
42
43 /**
44 * @var ClassCollector Helper class extracts class names from php files
45 */
46 protected $collector;
47
48 /**
49 * @var array Map of file shortpath to list of FQCN detected within file
50 */
51 protected $classes = [];
52
53 /**
54 * @var string The global variable to write output to
55 */
56 protected $variableName = 'wgAutoloadClasses';
57
58 /**
59 * @var array Map of FQCN to relative path(from self::$basepath)
60 */
61 protected $overrides = [];
62
63 /**
64 * Directories that should be excluded
65 *
66 * @var string[]
67 */
68 protected $excludePaths = [];
69
70 /**
71 * Configured PSR4 namespaces
72 *
73 * @var string[] namespace => path
74 */
75 protected $psr4Namespaces = [];
76
77 /**
78 * @param string $basepath Root path of the project being scanned for classes
79 * @param array|string $flags
80 *
81 * local - If this flag is set $wgAutoloadLocalClasses will be build instead
82 * of $wgAutoloadClasses
83 */
84 public function __construct( $basepath, $flags = [] ) {
85 if ( !is_array( $flags ) ) {
86 $flags = [ $flags ];
87 }
88 $this->basepath = self::normalizePathSeparator( realpath( $basepath ) );
89 $this->collector = new ClassCollector;
90 if ( in_array( 'local', $flags ) ) {
91 $this->variableName = 'wgAutoloadLocalClasses';
92 }
93 }
94
95 /**
96 * Directories that should be excluded
97 *
98 * @since 1.31
99 * @param string[] $paths
100 */
101 public function setExcludePaths( array $paths ) {
102 foreach ( $paths as $path ) {
103 $this->excludePaths[] = self::normalizePathSeparator( $path );
104 }
105 }
106
107 /**
108 * Set PSR4 namespaces
109 *
110 * Unlike self::setExcludePaths(), this will only skip outputting the
111 * autoloader entry when the namespace matches the path.
112 *
113 * @since 1.32
114 * @param string[] $namespaces Associative array mapping namespace to path
115 */
116 public function setPsr4Namespaces( array $namespaces ) {
117 foreach ( $namespaces as $ns => $path ) {
118 $ns = rtrim( $ns, '\\' ) . '\\';
119 $this->psr4Namespaces[$ns] = rtrim( self::normalizePathSeparator( $path ), '/' );
120 }
121 }
122
123 /**
124 * Whether the file should be excluded
125 *
126 * @param string $path File path
127 * @return bool
128 */
129 private function shouldExclude( $path ) {
130 foreach ( $this->excludePaths as $dir ) {
131 if ( strpos( $path, $dir ) === 0 ) {
132 return true;
133 }
134 }
135
136 return false;
137 }
138
139 /**
140 * Force a class to be autoloaded from a specific path, regardless of where
141 * or if it was detected.
142 *
143 * @param string $fqcn FQCN to force the location of
144 * @param string $inputPath Full path to the file containing the class
145 * @throws Exception
146 */
147 public function forceClassPath( $fqcn, $inputPath ) {
148 $path = self::normalizePathSeparator( realpath( $inputPath ) );
149 if ( !$path ) {
150 throw new \Exception( "Invalid path: $inputPath" );
151 }
152 $len = strlen( $this->basepath );
153 if ( substr( $path, 0, $len ) !== $this->basepath ) {
154 throw new \Exception( "Path is not within basepath: $inputPath" );
155 }
156 $shortpath = substr( $path, $len );
157 $this->overrides[$fqcn] = $shortpath;
158 }
159
160 /**
161 * @param string $inputPath Path to a php file to find classes within
162 * @throws Exception
163 */
164 public function readFile( $inputPath ) {
165 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
166 // reasonable for LocalSettings.php and similiar files to be symlinks
167 // to files that are outside of $this->basepath.
168 $inputPath = self::normalizePathSeparator( $inputPath );
169 $len = strlen( $this->basepath );
170 if ( substr( $inputPath, 0, $len ) !== $this->basepath ) {
171 throw new \Exception( "Path is not within basepath: $inputPath" );
172 }
173 if ( $this->shouldExclude( $inputPath ) ) {
174 return;
175 }
176 $result = $this->collector->getClasses(
177 file_get_contents( $inputPath )
178 );
179
180 // Filter out classes that will be found by PSR4
181 $result = array_filter( $result, function ( $class ) use ( $inputPath ) {
182 $parts = explode( '\\', $class );
183 for ( $i = count( $parts ) - 1; $i > 0; $i-- ) {
184 $ns = implode( '\\', array_slice( $parts, 0, $i ) ) . '\\';
185 if ( isset( $this->psr4Namespaces[$ns] ) ) {
186 $expectedPath = $this->psr4Namespaces[$ns] . '/'
187 . implode( '/', array_slice( $parts, $i ) )
188 . '.php';
189 if ( $inputPath === $expectedPath ) {
190 return false;
191 }
192 }
193 }
194
195 return true;
196 } );
197
198 if ( $result ) {
199 $shortpath = substr( $inputPath, $len );
200 $this->classes[$shortpath] = $result;
201 }
202 }
203
204 /**
205 * @param string $dir Path to a directory to recursively search
206 * for php files with either .php or .inc extensions
207 */
208 public function readDir( $dir ) {
209 $it = new RecursiveDirectoryIterator(
210 self::normalizePathSeparator( realpath( $dir ) ) );
211 $it = new RecursiveIteratorIterator( $it );
212
213 foreach ( $it as $path => $file ) {
214 $ext = pathinfo( $path, PATHINFO_EXTENSION );
215 // some older files in mw use .inc
216 if ( $ext === 'php' || $ext === 'inc' ) {
217 $this->readFile( $path );
218 }
219 }
220 }
221
222 /**
223 * Updates the AutoloadClasses field at the given
224 * filename.
225 *
226 * @param string $filename Filename of JSON
227 * extension/skin registration file
228 * @return string Updated Json of the file given as the $filename parameter
229 */
230 protected function generateJsonAutoload( $filename ) {
231 $key = 'AutoloadClasses';
232 $json = FormatJson::decode( file_get_contents( $filename ), true );
233 unset( $json[$key] );
234 // Inverting the key-value pairs so that they become of the
235 // format class-name : path when they get converted into json.
236 foreach ( $this->classes as $path => $contained ) {
237 foreach ( $contained as $fqcn ) {
238 // Using substr to remove the leading '/'
239 $json[$key][$fqcn] = substr( $path, 1 );
240 }
241 }
242 foreach ( $this->overrides as $path => $fqcn ) {
243 // Using substr to remove the leading '/'
244 $json[$key][$fqcn] = substr( $path, 1 );
245 }
246
247 // Sorting the list of autoload classes.
248 ksort( $json[$key] );
249
250 // Return the whole JSON file
251 return FormatJson::encode( $json, "\t", FormatJson::ALL_OK ) . "\n";
252 }
253
254 /**
255 * Generates a PHP file setting up autoload information.
256 *
257 * @param string $commandName Command name to include in comment
258 * @param string $filename of PHP file to put autoload information in.
259 * @return string
260 */
261 protected function generatePHPAutoload( $commandName, $filename ) {
262 // No existing JSON file found; update/generate PHP file
263 $content = [];
264
265 // We need to generate a line each rather than exporting the
266 // full array so __DIR__ can be prepended to all the paths
267 $format = "%s => __DIR__ . %s,";
268 foreach ( $this->classes as $path => $contained ) {
269 $exportedPath = var_export( $path, true );
270 foreach ( $contained as $fqcn ) {
271 $content[$fqcn] = sprintf(
272 $format,
273 var_export( $fqcn, true ),
274 $exportedPath
275 );
276 }
277 }
278
279 foreach ( $this->overrides as $fqcn => $path ) {
280 $content[$fqcn] = sprintf(
281 $format,
282 var_export( $fqcn, true ),
283 var_export( $path, true )
284 );
285 }
286
287 // sort for stable output
288 ksort( $content );
289
290 // extensions using this generator are appending to the existing
291 // autoload.
292 if ( $this->variableName === 'wgAutoloadClasses' ) {
293 $op = '+=';
294 } else {
295 $op = '=';
296 }
297
298 $output = implode( "\n\t", $content );
299 return <<<EOD
300 <?php
301 // This file is generated by $commandName, do not adjust manually
302 // phpcs:disable Generic.Files.LineLength
303 global \${$this->variableName};
304
305 \${$this->variableName} {$op} [
306 {$output}
307 ];
308
309 EOD;
310 }
311
312 /**
313 * Returns all known classes as a string, which can be used to put into a target
314 * file (e.g. extension.json, skin.json or autoload.php)
315 *
316 * @param string $commandName Value used in file comment to direct
317 * developers towards the appropriate way to update the autoload.
318 * @return string
319 */
320 public function getAutoload( $commandName = 'AutoloadGenerator' ) {
321 // We need to check whether an extension.json or skin.json exists or not, and
322 // incase it doesn't, update the autoload.php file.
323
324 $fileinfo = $this->getTargetFileinfo();
325
326 if ( $fileinfo['type'] === self::FILETYPE_JSON ) {
327 return $this->generateJsonAutoload( $fileinfo['filename'] );
328 } else {
329 return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
330 }
331 }
332
333 /**
334 * Returns the filename of the extension.json of skin.json, if there's any, or
335 * otherwise the path to the autoload.php file in an array as the "filename"
336 * key and with the type (AutoloadGenerator::FILETYPE_JSON or AutoloadGenerator::FILETYPE_PHP)
337 * of the file as the "type" key.
338 *
339 * @return array
340 */
341 public function getTargetFileinfo() {
342 $fileinfo = [
343 'filename' => $this->basepath . '/autoload.php',
344 'type' => self::FILETYPE_PHP
345 ];
346 if ( file_exists( $this->basepath . '/extension.json' ) ) {
347 $fileinfo = [
348 'filename' => $this->basepath . '/extension.json',
349 'type' => self::FILETYPE_JSON
350 ];
351 } elseif ( file_exists( $this->basepath . '/skin.json' ) ) {
352 $fileinfo = [
353 'filename' => $this->basepath . '/skin.json',
354 'type' => self::FILETYPE_JSON
355 ];
356 }
357
358 return $fileinfo;
359 }
360
361 /**
362 * Ensure that Unix-style path separators ("/") are used in the path.
363 *
364 * @param string $path
365 * @return string
366 */
367 protected static function normalizePathSeparator( $path ) {
368 return str_replace( '\\', '/', $path );
369 }
370
371 /**
372 * Initialize the source files and directories which are used for the MediaWiki default
373 * autoloader in {mw-base-dir}/autoload.php including:
374 * * includes/
375 * * languages/
376 * * maintenance/
377 * * mw-config/
378 * * /*.php
379 */
380 public function initMediaWikiDefault() {
381 foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
382 $this->readDir( $this->basepath . '/' . $dir );
383 }
384 foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
385 $this->readFile( $file );
386 }
387 }
388 }