Merge "registration: Only allow one extension to set a specific config setting"
[lhc/web/wiklou.git] / includes / utils / AutoloadGenerator.php
1 <?php
2
3 /**
4 * Accepts a list of files and directories to search for
5 * php files and generates $wgAutoloadLocalClasses or $wgAutoloadClasses
6 * lines for all detected classes. These lines are written out
7 * to an autoload.php file in the projects provided basedir.
8 *
9 * Usage:
10 *
11 * $gen = new AutoloadGenerator( __DIR__ );
12 * $gen->readDir( __DIR__ . '/includes' );
13 * $gen->readFile( __DIR__ . '/foo.php' )
14 * $gen->getAutoload();
15 */
16 class AutoloadGenerator {
17 const FILETYPE_JSON = 'json';
18 const FILETYPE_PHP = 'php';
19
20 /**
21 * @var string Root path of the project being scanned for classes
22 */
23 protected $basepath;
24
25 /**
26 * @var ClassCollector Helper class extracts class names from php files
27 */
28 protected $collector;
29
30 /**
31 * @var array Map of file shortpath to list of FQCN detected within file
32 */
33 protected $classes = [];
34
35 /**
36 * @var string The global variable to write output to
37 */
38 protected $variableName = 'wgAutoloadClasses';
39
40 /**
41 * @var array Map of FQCN to relative path(from self::$basepath)
42 */
43 protected $overrides = [];
44
45 /**
46 * @param string $basepath Root path of the project being scanned for classes
47 * @param array|string $flags
48 *
49 * local - If this flag is set $wgAutoloadLocalClasses will be build instead
50 * of $wgAutoloadClasses
51 */
52 public function __construct( $basepath, $flags = [] ) {
53 if ( !is_array( $flags ) ) {
54 $flags = [ $flags ];
55 }
56 $this->basepath = self::normalizePathSeparator( realpath( $basepath ) );
57 $this->collector = new ClassCollector;
58 if ( in_array( 'local', $flags ) ) {
59 $this->variableName = 'wgAutoloadLocalClasses';
60 }
61 }
62
63 /**
64 * Force a class to be autoloaded from a specific path, regardless of where
65 * or if it was detected.
66 *
67 * @param string $fqcn FQCN to force the location of
68 * @param string $inputPath Full path to the file containing the class
69 * @throws Exception
70 */
71 public function forceClassPath( $fqcn, $inputPath ) {
72 $path = self::normalizePathSeparator( realpath( $inputPath ) );
73 if ( !$path ) {
74 throw new \Exception( "Invalid path: $inputPath" );
75 }
76 $len = strlen( $this->basepath );
77 if ( substr( $path, 0, $len ) !== $this->basepath ) {
78 throw new \Exception( "Path is not within basepath: $inputPath" );
79 }
80 $shortpath = substr( $path, $len );
81 $this->overrides[$fqcn] = $shortpath;
82 }
83
84 /**
85 * @param string $inputPath Path to a php file to find classes within
86 * @throws Exception
87 */
88 public function readFile( $inputPath ) {
89 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
90 // reasonable for LocalSettings.php and similiar files to be symlinks
91 // to files that are outside of $this->basepath.
92 $inputPath = self::normalizePathSeparator( $inputPath );
93 $len = strlen( $this->basepath );
94 if ( substr( $inputPath, 0, $len ) !== $this->basepath ) {
95 throw new \Exception( "Path is not within basepath: $inputPath" );
96 }
97 $result = $this->collector->getClasses(
98 file_get_contents( $inputPath )
99 );
100 if ( $result ) {
101 $shortpath = substr( $inputPath, $len );
102 $this->classes[$shortpath] = $result;
103 }
104 }
105
106 /**
107 * @param string $dir Path to a directory to recursively search
108 * for php files with either .php or .inc extensions
109 */
110 public function readDir( $dir ) {
111 $it = new RecursiveDirectoryIterator(
112 self::normalizePathSeparator( realpath( $dir ) ) );
113 $it = new RecursiveIteratorIterator( $it );
114
115 foreach ( $it as $path => $file ) {
116 $ext = pathinfo( $path, PATHINFO_EXTENSION );
117 // some older files in mw use .inc
118 if ( $ext === 'php' || $ext === 'inc' ) {
119 $this->readFile( $path );
120 }
121 }
122 }
123
124 /**
125 * Updates the AutoloadClasses field at the given
126 * filename.
127 *
128 * @param string $filename Filename of JSON
129 * extension/skin registration file
130 * @return string Updated Json of the file given as the $filename parameter
131 */
132 protected function generateJsonAutoload( $filename ) {
133 $key = 'AutoloadClasses';
134 $json = FormatJson::decode( file_get_contents( $filename ), true );
135 unset( $json[$key] );
136 // Inverting the key-value pairs so that they become of the
137 // format class-name : path when they get converted into json.
138 foreach ( $this->classes as $path => $contained ) {
139 foreach ( $contained as $fqcn ) {
140 // Using substr to remove the leading '/'
141 $json[$key][$fqcn] = substr( $path, 1 );
142 }
143 }
144 foreach ( $this->overrides as $path => $fqcn ) {
145 // Using substr to remove the leading '/'
146 $json[$key][$fqcn] = substr( $path, 1 );
147 }
148
149 // Sorting the list of autoload classes.
150 ksort( $json[$key] );
151
152 // Return the whole JSON file
153 return FormatJson::encode( $json, "\t", FormatJson::ALL_OK ) . "\n";
154 }
155
156 /**
157 * Generates a PHP file setting up autoload information.
158 *
159 * @param string $commandName Command name to include in comment
160 * @param string $filename of PHP file to put autoload information in.
161 * @return string
162 */
163 protected function generatePHPAutoload( $commandName, $filename ) {
164 // No existing JSON file found; update/generate PHP file
165 $content = [];
166
167 // We need to generate a line each rather than exporting the
168 // full array so __DIR__ can be prepended to all the paths
169 $format = "%s => __DIR__ . %s,";
170 foreach ( $this->classes as $path => $contained ) {
171 $exportedPath = var_export( $path, true );
172 foreach ( $contained as $fqcn ) {
173 $content[$fqcn] = sprintf(
174 $format,
175 var_export( $fqcn, true ),
176 $exportedPath
177 );
178 }
179 }
180
181 foreach ( $this->overrides as $fqcn => $path ) {
182 $content[$fqcn] = sprintf(
183 $format,
184 var_export( $fqcn, true ),
185 var_export( $path, true )
186 );
187 }
188
189 // sort for stable output
190 ksort( $content );
191
192 // extensions using this generator are appending to the existing
193 // autoload.
194 if ( $this->variableName === 'wgAutoloadClasses' ) {
195 $op = '+=';
196 } else {
197 $op = '=';
198 }
199
200 $output = implode( "\n\t", $content );
201 return
202 <<<EOD
203 <?php
204 // This file is generated by $commandName, do not adjust manually
205 // @codingStandardsIgnoreFile
206 global \${$this->variableName};
207
208 \${$this->variableName} {$op} [
209 {$output}
210 ];
211
212 EOD;
213 }
214
215 /**
216 * Returns all known classes as a string, which can be used to put into a target
217 * file (e.g. extension.json, skin.json or autoload.php)
218 *
219 * @param string $commandName Value used in file comment to direct
220 * developers towards the appropriate way to update the autoload.
221 * @return string
222 */
223 public function getAutoload( $commandName = 'AutoloadGenerator' ) {
224 // We need to check whether an extenson.json or skin.json exists or not, and
225 // incase it doesn't, update the autoload.php file.
226
227 $fileinfo = $this->getTargetFileinfo();
228
229 if ( $fileinfo['type'] === self::FILETYPE_JSON ) {
230 return $this->generateJsonAutoload( $fileinfo['filename'] );
231 } else {
232 return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
233 }
234 }
235
236 /**
237 * Returns the filename of the extension.json of skin.json, if there's any, or
238 * otherwise the path to the autoload.php file in an array as the "filename"
239 * key and with the type (AutoloadGenerator::FILETYPE_JSON or AutoloadGenerator::FILETYPE_PHP)
240 * of the file as the "type" key.
241 *
242 * @return array
243 */
244 public function getTargetFileinfo() {
245 $fileinfo = [
246 'filename' => $this->basepath . '/autoload.php',
247 'type' => self::FILETYPE_PHP
248 ];
249 if ( file_exists( $this->basepath . '/extension.json' ) ) {
250 $fileinfo = [
251 'filename' => $this->basepath . '/extension.json',
252 'type' => self::FILETYPE_JSON
253 ];
254 } elseif ( file_exists( $this->basepath . '/skin.json' ) ) {
255 $fileinfo = [
256 'filename' => $this->basepath . '/skin.json',
257 'type' => self::FILETYPE_JSON
258 ];
259 }
260
261 return $fileinfo;
262 }
263
264 /**
265 * Ensure that Unix-style path separators ("/") are used in the path.
266 *
267 * @param string $path
268 * @return string
269 */
270 protected static function normalizePathSeparator( $path ) {
271 return str_replace( '\\', '/', $path );
272 }
273
274 /**
275 * Initialize the source files and directories which are used for the MediaWiki default
276 * autoloader in {mw-base-dir}/autoload.php including:
277 * * includes/
278 * * languages/
279 * * maintenance/
280 * * mw-config/
281 * * /*.php
282 */
283 public function initMediaWikiDefault() {
284 foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
285 $this->readDir( $this->basepath . '/' . $dir );
286 }
287 foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
288 $this->readFile( $file );
289 }
290 }
291 }
292
293 /**
294 * Reads PHP code and returns the FQCN of every class defined within it.
295 */
296 class ClassCollector {
297
298 /**
299 * @var string Current namespace
300 */
301 protected $namespace = '';
302
303 /**
304 * @var array List of FQCN detected in this pass
305 */
306 protected $classes;
307
308 /**
309 * @var array Token from token_get_all() that started an expect sequence
310 */
311 protected $startToken;
312
313 /**
314 * @var array List of tokens that are members of the current expect sequence
315 */
316 protected $tokens;
317
318 /**
319 * @var array Class alias with target/name fields
320 */
321 protected $alias;
322
323 /**
324 * @param string $code PHP code (including <?php) to detect class names from
325 * @return array List of FQCN detected within the tokens
326 */
327 public function getClasses( $code ) {
328 $this->namespace = '';
329 $this->classes = [];
330 $this->startToken = null;
331 $this->alias = null;
332 $this->tokens = [];
333
334 foreach ( token_get_all( $code ) as $token ) {
335 if ( $this->startToken === null ) {
336 $this->tryBeginExpect( $token );
337 } else {
338 $this->tryEndExpect( $token );
339 }
340 }
341
342 return $this->classes;
343 }
344
345 /**
346 * Determine if $token begins the next expect sequence.
347 *
348 * @param array $token
349 */
350 protected function tryBeginExpect( $token ) {
351 if ( is_string( $token ) ) {
352 return;
353 }
354 // Note: When changing class name discovery logic,
355 // AutoLoaderTest.php may also need to be updated.
356 switch ( $token[0] ) {
357 case T_NAMESPACE:
358 case T_CLASS:
359 case T_INTERFACE:
360 case T_TRAIT:
361 case T_DOUBLE_COLON:
362 $this->startToken = $token;
363 break;
364 case T_STRING:
365 if ( $token[1] === 'class_alias' ) {
366 $this->startToken = $token;
367 $this->alias = [];
368 }
369 }
370 }
371
372 /**
373 * Accepts the next token in an expect sequence
374 *
375 * @param array $token
376 */
377 protected function tryEndExpect( $token ) {
378 switch ( $this->startToken[0] ) {
379 case T_DOUBLE_COLON:
380 // Skip over T_CLASS after T_DOUBLE_COLON because this is something like
381 // "self::static" which accesses the class name. It doens't define a new class.
382 $this->startToken = null;
383 break;
384 case T_NAMESPACE:
385 if ( $token === ';' || $token === '{' ) {
386 $this->namespace = $this->implodeTokens() . '\\';
387 } else {
388 $this->tokens[] = $token;
389 }
390 break;
391
392 case T_STRING:
393 if ( $this->alias !== null ) {
394 // Flow 1 - Two string literals:
395 // - T_STRING class_alias
396 // - '('
397 // - T_CONSTANT_ENCAPSED_STRING 'TargetClass'
398 // - ','
399 // - T_WHITESPACE
400 // - T_CONSTANT_ENCAPSED_STRING 'AliasName'
401 // - ')'
402 // Flow 2 - Use of ::class syntax for first parameter
403 // - T_STRING class_alias
404 // - '('
405 // - T_STRING TargetClass
406 // - T_DOUBLE_COLON ::
407 // - T_CLASS class
408 // - ','
409 // - T_WHITESPACE
410 // - T_CONSTANT_ENCAPSED_STRING 'AliasName'
411 // - ')'
412 if ( $token === '(' ) {
413 // Start of a function call to class_alias()
414 $this->alias = [ 'target' => false, 'name' => false ];
415 } elseif ( $token === ',' ) {
416 // Record that we're past the first parameter
417 if ( $this->alias['target'] === false ) {
418 $this->alias['target'] = true;
419 }
420 } elseif ( is_array( $token ) && $token[0] === T_CONSTANT_ENCAPSED_STRING ) {
421 if ( $this->alias['target'] === true ) {
422 // We already saw a first argument, this must be the second.
423 // Strip quotes from the string literal.
424 $this->alias['name'] = substr( $token[1], 1, -1 );
425 }
426 } elseif ( $token === ')' ) {
427 // End of function call
428 $this->classes[] = $this->alias['name'];
429 $this->alias = null;
430 $this->startToken = null;
431 } elseif ( !is_array( $token ) || (
432 $token[0] !== T_STRING &&
433 $token[0] !== T_DOUBLE_COLON &&
434 $token[0] !== T_CLASS &&
435 $token[0] !== T_WHITESPACE
436 ) ) {
437 // Ignore this call to class_alias() - compat/Timestamp.php
438 $this->alias = null;
439 $this->startToken = null;
440 }
441 }
442 break;
443
444 case T_CLASS:
445 case T_INTERFACE:
446 case T_TRAIT:
447 $this->tokens[] = $token;
448 if ( is_array( $token ) && $token[0] === T_STRING ) {
449 $this->classes[] = $this->namespace . $this->implodeTokens();
450 }
451 }
452 }
453
454 /**
455 * Returns the string representation of the tokens within the
456 * current expect sequence and resets the sequence.
457 *
458 * @return string
459 */
460 protected function implodeTokens() {
461 $content = [];
462 foreach ( $this->tokens as $token ) {
463 $content[] = is_string( $token ) ? $token : $token[1];
464 }
465
466 $this->tokens = [];
467 $this->startToken = null;
468
469 return trim( implode( '', $content ), " \n\t" );
470 }
471 }