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 foreach ( $paths as $path ) {
78 $this->excludePaths
[] = self
::normalizePathSeparator( $path );
83 * Whether the file should be excluded
85 * @param string $path File path
88 private function shouldExclude( $path ) {
89 foreach ( $this->excludePaths
as $dir ) {
90 if ( strpos( $path, $dir ) === 0 ) {
99 * Force a class to be autoloaded from a specific path, regardless of where
100 * or if it was detected.
102 * @param string $fqcn FQCN to force the location of
103 * @param string $inputPath Full path to the file containing the class
106 public function forceClassPath( $fqcn, $inputPath ) {
107 $path = self
::normalizePathSeparator( realpath( $inputPath ) );
109 throw new \
Exception( "Invalid path: $inputPath" );
111 $len = strlen( $this->basepath
);
112 if ( substr( $path, 0, $len ) !== $this->basepath
) {
113 throw new \
Exception( "Path is not within basepath: $inputPath" );
115 $shortpath = substr( $path, $len );
116 $this->overrides
[$fqcn] = $shortpath;
120 * @param string $inputPath Path to a php file to find classes within
123 public function readFile( $inputPath ) {
124 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
125 // reasonable for LocalSettings.php and similiar files to be symlinks
126 // to files that are outside of $this->basepath.
127 $inputPath = self
::normalizePathSeparator( $inputPath );
128 $len = strlen( $this->basepath
);
129 if ( substr( $inputPath, 0, $len ) !== $this->basepath
) {
130 throw new \
Exception( "Path is not within basepath: $inputPath" );
132 if ( $this->shouldExclude( $inputPath ) ) {
135 $result = $this->collector
->getClasses(
136 file_get_contents( $inputPath )
139 $shortpath = substr( $inputPath, $len );
140 $this->classes
[$shortpath] = $result;
145 * @param string $dir Path to a directory to recursively search
146 * for php files with either .php or .inc extensions
148 public function readDir( $dir ) {
149 $it = new RecursiveDirectoryIterator(
150 self
::normalizePathSeparator( realpath( $dir ) ) );
151 $it = new RecursiveIteratorIterator( $it );
153 foreach ( $it as $path => $file ) {
154 $ext = pathinfo( $path, PATHINFO_EXTENSION
);
155 // some older files in mw use .inc
156 if ( $ext === 'php' ||
$ext === 'inc' ) {
157 $this->readFile( $path );
163 * Updates the AutoloadClasses field at the given
166 * @param string $filename Filename of JSON
167 * extension/skin registration file
168 * @return string Updated Json of the file given as the $filename parameter
170 protected function generateJsonAutoload( $filename ) {
171 $key = 'AutoloadClasses';
172 $json = FormatJson
::decode( file_get_contents( $filename ), true );
173 unset( $json[$key] );
174 // Inverting the key-value pairs so that they become of the
175 // format class-name : path when they get converted into json.
176 foreach ( $this->classes
as $path => $contained ) {
177 foreach ( $contained as $fqcn ) {
178 // Using substr to remove the leading '/'
179 $json[$key][$fqcn] = substr( $path, 1 );
182 foreach ( $this->overrides
as $path => $fqcn ) {
183 // Using substr to remove the leading '/'
184 $json[$key][$fqcn] = substr( $path, 1 );
187 // Sorting the list of autoload classes.
188 ksort( $json[$key] );
190 // Return the whole JSON file
191 return FormatJson
::encode( $json, "\t", FormatJson
::ALL_OK
) . "\n";
195 * Generates a PHP file setting up autoload information.
197 * @param string $commandName Command name to include in comment
198 * @param string $filename of PHP file to put autoload information in.
201 protected function generatePHPAutoload( $commandName, $filename ) {
202 // No existing JSON file found; update/generate PHP file
205 // We need to generate a line each rather than exporting the
206 // full array so __DIR__ can be prepended to all the paths
207 $format = "%s => __DIR__ . %s,";
208 foreach ( $this->classes
as $path => $contained ) {
209 $exportedPath = var_export( $path, true );
210 foreach ( $contained as $fqcn ) {
211 $content[$fqcn] = sprintf(
213 var_export( $fqcn, true ),
219 foreach ( $this->overrides
as $fqcn => $path ) {
220 $content[$fqcn] = sprintf(
222 var_export( $fqcn, true ),
223 var_export( $path, true )
227 // sort for stable output
230 // extensions using this generator are appending to the existing
232 if ( $this->variableName
=== 'wgAutoloadClasses' ) {
238 $output = implode( "\n\t", $content );
241 // This file is generated by $commandName, do not adjust manually
242 // phpcs:disable Generic.Files.LineLength
243 global \${$this->variableName};
245 \${$this->variableName} {$op} [
253 * Returns all known classes as a string, which can be used to put into a target
254 * file (e.g. extension.json, skin.json or autoload.php)
256 * @param string $commandName Value used in file comment to direct
257 * developers towards the appropriate way to update the autoload.
260 public function getAutoload( $commandName = 'AutoloadGenerator' ) {
261 // We need to check whether an extenson.json or skin.json exists or not, and
262 // incase it doesn't, update the autoload.php file.
264 $fileinfo = $this->getTargetFileinfo();
266 if ( $fileinfo['type'] === self
::FILETYPE_JSON
) {
267 return $this->generateJsonAutoload( $fileinfo['filename'] );
269 return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
274 * Returns the filename of the extension.json of skin.json, if there's any, or
275 * otherwise the path to the autoload.php file in an array as the "filename"
276 * key and with the type (AutoloadGenerator::FILETYPE_JSON or AutoloadGenerator::FILETYPE_PHP)
277 * of the file as the "type" key.
281 public function getTargetFileinfo() {
283 'filename' => $this->basepath
. '/autoload.php',
284 'type' => self
::FILETYPE_PHP
286 if ( file_exists( $this->basepath
. '/extension.json' ) ) {
288 'filename' => $this->basepath
. '/extension.json',
289 'type' => self
::FILETYPE_JSON
291 } elseif ( file_exists( $this->basepath
. '/skin.json' ) ) {
293 'filename' => $this->basepath
. '/skin.json',
294 'type' => self
::FILETYPE_JSON
302 * Ensure that Unix-style path separators ("/") are used in the path.
304 * @param string $path
307 protected static function normalizePathSeparator( $path ) {
308 return str_replace( '\\', '/', $path );
312 * Initialize the source files and directories which are used for the MediaWiki default
313 * autoloader in {mw-base-dir}/autoload.php including:
320 public function initMediaWikiDefault() {
321 foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
322 $this->readDir( $this->basepath
. '/' . $dir );
324 foreach ( glob( $this->basepath
. '/*.php' ) as $file ) {
325 $this->readFile( $file );
331 * Reads PHP code and returns the FQCN of every class defined within it.
333 class ClassCollector
{
336 * @var string Current namespace
338 protected $namespace = '';
341 * @var array List of FQCN detected in this pass
346 * @var array Token from token_get_all() that started an expect sequence
348 protected $startToken;
351 * @var array List of tokens that are members of the current expect sequence
356 * @var array Class alias with target/name fields
361 * @param string $code PHP code (including <?php) to detect class names from
362 * @return array List of FQCN detected within the tokens
364 public function getClasses( $code ) {
365 $this->namespace = '';
367 $this->startToken
= null;
371 foreach ( token_get_all( $code ) as $token ) {
372 if ( $this->startToken
=== null ) {
373 $this->tryBeginExpect( $token );
375 $this->tryEndExpect( $token );
379 return $this->classes
;
383 * Determine if $token begins the next expect sequence.
385 * @param array $token
387 protected function tryBeginExpect( $token ) {
388 if ( is_string( $token ) ) {
391 // Note: When changing class name discovery logic,
392 // AutoLoaderStructureTest.php may also need to be updated.
393 switch ( $token[0] ) {
400 $this->startToken
= $token;
403 if ( $token[1] === 'class_alias' ) {
404 $this->startToken
= $token;
411 * Accepts the next token in an expect sequence
413 * @param array $token
415 protected function tryEndExpect( $token ) {
416 switch ( $this->startToken
[0] ) {
418 // Skip over T_CLASS after T_DOUBLE_COLON because this is something like
419 // "self::static" which accesses the class name. It doens't define a new class.
420 $this->startToken
= null;
423 // Skip over T_CLASS after T_NEW because this is a PHP 7 anonymous class.
424 if ( !is_array( $token ) ||
$token[0] !== T_WHITESPACE
) {
425 $this->startToken
= null;
429 if ( $token === ';' ||
$token === '{' ) {
430 $this->namespace = $this->implodeTokens() . '\\';
432 $this->tokens
[] = $token;
437 if ( $this->alias
!== null ) {
438 // Flow 1 - Two string literals:
439 // - T_STRING class_alias
441 // - T_CONSTANT_ENCAPSED_STRING 'TargetClass'
444 // - T_CONSTANT_ENCAPSED_STRING 'AliasName'
446 // Flow 2 - Use of ::class syntax for first parameter
447 // - T_STRING class_alias
449 // - T_STRING TargetClass
450 // - T_DOUBLE_COLON ::
454 // - T_CONSTANT_ENCAPSED_STRING 'AliasName'
456 if ( $token === '(' ) {
457 // Start of a function call to class_alias()
458 $this->alias
= [ 'target' => false, 'name' => false ];
459 } elseif ( $token === ',' ) {
460 // Record that we're past the first parameter
461 if ( $this->alias
['target'] === false ) {
462 $this->alias
['target'] = true;
464 } elseif ( is_array( $token ) && $token[0] === T_CONSTANT_ENCAPSED_STRING
) {
465 if ( $this->alias
['target'] === true ) {
466 // We already saw a first argument, this must be the second.
467 // Strip quotes from the string literal.
468 $this->alias
['name'] = substr( $token[1], 1, -1 );
470 } elseif ( $token === ')' ) {
471 // End of function call
472 $this->classes
[] = $this->alias
['name'];
474 $this->startToken
= null;
475 } elseif ( !is_array( $token ) ||
(
476 $token[0] !== T_STRING
&&
477 $token[0] !== T_DOUBLE_COLON
&&
478 $token[0] !== T_CLASS
&&
479 $token[0] !== T_WHITESPACE
481 // Ignore this call to class_alias() - compat/Timestamp.php
483 $this->startToken
= null;
491 $this->tokens
[] = $token;
492 if ( is_array( $token ) && $token[0] === T_STRING
) {
493 $this->classes
[] = $this->namespace . $this->implodeTokens();
499 * Returns the string representation of the tokens within the
500 * current expect sequence and resets the sequence.
504 protected function implodeTokens() {
506 foreach ( $this->tokens
as $token ) {
507 $content[] = is_string( $token ) ?
$token : $token[1];
511 $this->startToken
= null;
513 return trim( implode( '', $content ), " \n\t" );