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.
11 * $gen = new AutoloadGenerator( __DIR__ );
12 * $gen->readDir( __DIR__ . '/includes' );
13 * $gen->readFile( __DIR__ . '/foo.php' )
14 * $gen->getAutoload();
16 class AutoloadGenerator
{
17 const FILETYPE_JSON
= 'json';
18 const FILETYPE_PHP
= 'php';
21 * @var string Root path of the project being scanned for classes
26 * @var ClassCollector Helper class extracts class names from php files
31 * @var array Map of file shortpath to list of FQCN detected within file
33 protected $classes = [];
36 * @var string The global variable to write output to
38 protected $variableName = 'wgAutoloadClasses';
41 * @var array Map of FQCN to relative path(from self::$basepath)
43 protected $overrides = [];
46 * Directories that should be excluded
50 protected $excludePaths = [];
53 * @param string $basepath Root path of the project being scanned for classes
54 * @param array|string $flags
56 * local - If this flag is set $wgAutoloadLocalClasses will be build instead
57 * of $wgAutoloadClasses
59 public function __construct( $basepath, $flags = [] ) {
60 if ( !is_array( $flags ) ) {
63 $this->basepath
= self
::normalizePathSeparator( realpath( $basepath ) );
64 $this->collector
= new ClassCollector
;
65 if ( in_array( 'local', $flags ) ) {
66 $this->variableName
= 'wgAutoloadLocalClasses';
71 * Directories that should be excluded
74 * @param string[] $paths
76 public function setExcludePaths( array $paths ) {
77 $this->excludePaths
= $paths;
81 * Whether the file should be excluded
83 * @param string $path File path
86 private function shouldExclude( $path ) {
87 foreach ( $this->excludePaths
as $dir ) {
88 if ( strpos( $path, $dir ) === 0 ) {
97 * Force a class to be autoloaded from a specific path, regardless of where
98 * or if it was detected.
100 * @param string $fqcn FQCN to force the location of
101 * @param string $inputPath Full path to the file containing the class
104 public function forceClassPath( $fqcn, $inputPath ) {
105 $path = self
::normalizePathSeparator( realpath( $inputPath ) );
107 throw new \
Exception( "Invalid path: $inputPath" );
109 $len = strlen( $this->basepath
);
110 if ( substr( $path, 0, $len ) !== $this->basepath
) {
111 throw new \
Exception( "Path is not within basepath: $inputPath" );
113 $shortpath = substr( $path, $len );
114 $this->overrides
[$fqcn] = $shortpath;
118 * @param string $inputPath Path to a php file to find classes within
121 public function readFile( $inputPath ) {
122 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
123 // reasonable for LocalSettings.php and similiar files to be symlinks
124 // to files that are outside of $this->basepath.
125 $inputPath = self
::normalizePathSeparator( $inputPath );
126 $len = strlen( $this->basepath
);
127 if ( substr( $inputPath, 0, $len ) !== $this->basepath
) {
128 throw new \
Exception( "Path is not within basepath: $inputPath" );
130 if ( $this->shouldExclude( $inputPath ) ) {
133 $result = $this->collector
->getClasses(
134 file_get_contents( $inputPath )
137 $shortpath = substr( $inputPath, $len );
138 $this->classes
[$shortpath] = $result;
143 * @param string $dir Path to a directory to recursively search
144 * for php files with either .php or .inc extensions
146 public function readDir( $dir ) {
147 $it = new RecursiveDirectoryIterator(
148 self
::normalizePathSeparator( realpath( $dir ) ) );
149 $it = new RecursiveIteratorIterator( $it );
151 foreach ( $it as $path => $file ) {
152 $ext = pathinfo( $path, PATHINFO_EXTENSION
);
153 // some older files in mw use .inc
154 if ( $ext === 'php' ||
$ext === 'inc' ) {
155 $this->readFile( $path );
161 * Updates the AutoloadClasses field at the given
164 * @param string $filename Filename of JSON
165 * extension/skin registration file
166 * @return string Updated Json of the file given as the $filename parameter
168 protected function generateJsonAutoload( $filename ) {
169 $key = 'AutoloadClasses';
170 $json = FormatJson
::decode( file_get_contents( $filename ), true );
171 unset( $json[$key] );
172 // Inverting the key-value pairs so that they become of the
173 // format class-name : path when they get converted into json.
174 foreach ( $this->classes
as $path => $contained ) {
175 foreach ( $contained as $fqcn ) {
176 // Using substr to remove the leading '/'
177 $json[$key][$fqcn] = substr( $path, 1 );
180 foreach ( $this->overrides
as $path => $fqcn ) {
181 // Using substr to remove the leading '/'
182 $json[$key][$fqcn] = substr( $path, 1 );
185 // Sorting the list of autoload classes.
186 ksort( $json[$key] );
188 // Return the whole JSON file
189 return FormatJson
::encode( $json, "\t", FormatJson
::ALL_OK
) . "\n";
193 * Generates a PHP file setting up autoload information.
195 * @param string $commandName Command name to include in comment
196 * @param string $filename of PHP file to put autoload information in.
199 protected function generatePHPAutoload( $commandName, $filename ) {
200 // No existing JSON file found; update/generate PHP file
203 // We need to generate a line each rather than exporting the
204 // full array so __DIR__ can be prepended to all the paths
205 $format = "%s => __DIR__ . %s,";
206 foreach ( $this->classes
as $path => $contained ) {
207 $exportedPath = var_export( $path, true );
208 foreach ( $contained as $fqcn ) {
209 $content[$fqcn] = sprintf(
211 var_export( $fqcn, true ),
217 foreach ( $this->overrides
as $fqcn => $path ) {
218 $content[$fqcn] = sprintf(
220 var_export( $fqcn, true ),
221 var_export( $path, true )
225 // sort for stable output
228 // extensions using this generator are appending to the existing
230 if ( $this->variableName
=== 'wgAutoloadClasses' ) {
236 $output = implode( "\n\t", $content );
240 // This file is generated by $commandName, do not adjust manually
241 // @codingStandardsIgnoreFile
242 global \${$this->variableName};
244 \${$this->variableName} {$op} [
252 * Returns all known classes as a string, which can be used to put into a target
253 * file (e.g. extension.json, skin.json or autoload.php)
255 * @param string $commandName Value used in file comment to direct
256 * developers towards the appropriate way to update the autoload.
259 public function getAutoload( $commandName = 'AutoloadGenerator' ) {
260 // We need to check whether an extenson.json or skin.json exists or not, and
261 // incase it doesn't, update the autoload.php file.
263 $fileinfo = $this->getTargetFileinfo();
265 if ( $fileinfo['type'] === self
::FILETYPE_JSON
) {
266 return $this->generateJsonAutoload( $fileinfo['filename'] );
268 return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
273 * Returns the filename of the extension.json of skin.json, if there's any, or
274 * otherwise the path to the autoload.php file in an array as the "filename"
275 * key and with the type (AutoloadGenerator::FILETYPE_JSON or AutoloadGenerator::FILETYPE_PHP)
276 * of the file as the "type" key.
280 public function getTargetFileinfo() {
282 'filename' => $this->basepath
. '/autoload.php',
283 'type' => self
::FILETYPE_PHP
285 if ( file_exists( $this->basepath
. '/extension.json' ) ) {
287 'filename' => $this->basepath
. '/extension.json',
288 'type' => self
::FILETYPE_JSON
290 } elseif ( file_exists( $this->basepath
. '/skin.json' ) ) {
292 'filename' => $this->basepath
. '/skin.json',
293 'type' => self
::FILETYPE_JSON
301 * Ensure that Unix-style path separators ("/") are used in the path.
303 * @param string $path
306 protected static function normalizePathSeparator( $path ) {
307 return str_replace( '\\', '/', $path );
311 * Initialize the source files and directories which are used for the MediaWiki default
312 * autoloader in {mw-base-dir}/autoload.php including:
319 public function initMediaWikiDefault() {
320 foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
321 $this->readDir( $this->basepath
. '/' . $dir );
323 foreach ( glob( $this->basepath
. '/*.php' ) as $file ) {
324 $this->readFile( $file );
330 * Reads PHP code and returns the FQCN of every class defined within it.
332 class ClassCollector
{
335 * @var string Current namespace
337 protected $namespace = '';
340 * @var array List of FQCN detected in this pass
345 * @var array Token from token_get_all() that started an expect sequence
347 protected $startToken;
350 * @var array List of tokens that are members of the current expect sequence
355 * @var array Class alias with target/name fields
360 * @param string $code PHP code (including <?php) to detect class names from
361 * @return array List of FQCN detected within the tokens
363 public function getClasses( $code ) {
364 $this->namespace = '';
366 $this->startToken
= null;
370 foreach ( token_get_all( $code ) as $token ) {
371 if ( $this->startToken
=== null ) {
372 $this->tryBeginExpect( $token );
374 $this->tryEndExpect( $token );
378 return $this->classes
;
382 * Determine if $token begins the next expect sequence.
384 * @param array $token
386 protected function tryBeginExpect( $token ) {
387 if ( is_string( $token ) ) {
390 // Note: When changing class name discovery logic,
391 // AutoLoaderTest.php may also need to be updated.
392 switch ( $token[0] ) {
398 $this->startToken
= $token;
401 if ( $token[1] === 'class_alias' ) {
402 $this->startToken
= $token;
409 * Accepts the next token in an expect sequence
411 * @param array $token
413 protected function tryEndExpect( $token ) {
414 switch ( $this->startToken
[0] ) {
416 // Skip over T_CLASS after T_DOUBLE_COLON because this is something like
417 // "self::static" which accesses the class name. It doens't define a new class.
418 $this->startToken
= null;
421 if ( $token === ';' ||
$token === '{' ) {
422 $this->namespace = $this->implodeTokens() . '\\';
424 $this->tokens
[] = $token;
429 if ( $this->alias
!== null ) {
430 // Flow 1 - Two string literals:
431 // - T_STRING class_alias
433 // - T_CONSTANT_ENCAPSED_STRING 'TargetClass'
436 // - T_CONSTANT_ENCAPSED_STRING 'AliasName'
438 // Flow 2 - Use of ::class syntax for first parameter
439 // - T_STRING class_alias
441 // - T_STRING TargetClass
442 // - T_DOUBLE_COLON ::
446 // - T_CONSTANT_ENCAPSED_STRING 'AliasName'
448 if ( $token === '(' ) {
449 // Start of a function call to class_alias()
450 $this->alias
= [ 'target' => false, 'name' => false ];
451 } elseif ( $token === ',' ) {
452 // Record that we're past the first parameter
453 if ( $this->alias
['target'] === false ) {
454 $this->alias
['target'] = true;
456 } elseif ( is_array( $token ) && $token[0] === T_CONSTANT_ENCAPSED_STRING
) {
457 if ( $this->alias
['target'] === true ) {
458 // We already saw a first argument, this must be the second.
459 // Strip quotes from the string literal.
460 $this->alias
['name'] = substr( $token[1], 1, -1 );
462 } elseif ( $token === ')' ) {
463 // End of function call
464 $this->classes
[] = $this->alias
['name'];
466 $this->startToken
= null;
467 } elseif ( !is_array( $token ) ||
(
468 $token[0] !== T_STRING
&&
469 $token[0] !== T_DOUBLE_COLON
&&
470 $token[0] !== T_CLASS
&&
471 $token[0] !== T_WHITESPACE
473 // Ignore this call to class_alias() - compat/Timestamp.php
475 $this->startToken
= null;
483 $this->tokens
[] = $token;
484 if ( is_array( $token ) && $token[0] === T_STRING
) {
485 $this->classes
[] = $this->namespace . $this->implodeTokens();
491 * Returns the string representation of the tokens within the
492 * current expect sequence and resets the sequence.
496 protected function implodeTokens() {
498 foreach ( $this->tokens
as $token ) {
499 $content[] = is_string( $token ) ?
$token : $token[1];
503 $this->startToken
= null;
505 return trim( implode( '', $content ), " \n\t" );