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->generateAutoload();
16 class AutoloadGenerator
{
18 * @var string Root path of the project being scanned for classes
23 * @var ClassCollector Helper class extracts class names from php files
28 * @var array Map of file shortpath to list of FQCN detected within file
30 protected $classes = [];
33 * @var string The global variable to write output to
35 protected $variableName = 'wgAutoloadClasses';
38 * @var array Map of FQCN to relative path(from self::$basepath)
40 protected $overrides = [];
43 * @param string $basepath Root path of the project being scanned for classes
44 * @param array|string $flags
46 * local - If this flag is set $wgAutoloadLocalClasses will be build instead
47 * of $wgAutoloadClasses
49 public function __construct( $basepath, $flags = [] ) {
50 if ( !is_array( $flags ) ) {
53 $this->basepath
= self
::normalizePathSeparator( realpath( $basepath ) );
54 $this->collector
= new ClassCollector
;
55 if ( in_array( 'local', $flags ) ) {
56 $this->variableName
= 'wgAutoloadLocalClasses';
61 * Force a class to be autoloaded from a specific path, regardless of where
62 * or if it was detected.
64 * @param string $fqcn FQCN to force the location of
65 * @param string $inputPath Full path to the file containing the class
68 public function forceClassPath( $fqcn, $inputPath ) {
69 $path = self
::normalizePathSeparator( realpath( $inputPath ) );
71 throw new \
Exception( "Invalid path: $inputPath" );
73 $len = strlen( $this->basepath
);
74 if ( substr( $path, 0, $len ) !== $this->basepath
) {
75 throw new \
Exception( "Path is not within basepath: $inputPath" );
77 $shortpath = substr( $path, $len );
78 $this->overrides
[$fqcn] = $shortpath;
82 * @param string $inputPath Path to a php file to find classes within
85 public function readFile( $inputPath ) {
86 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
87 // reasonable for LocalSettings.php and similiar files to be symlinks
88 // to files that are outside of $this->basepath.
89 $inputPath = self
::normalizePathSeparator( $inputPath );
90 $len = strlen( $this->basepath
);
91 if ( substr( $inputPath, 0, $len ) !== $this->basepath
) {
92 throw new \
Exception( "Path is not within basepath: $inputPath" );
94 $result = $this->collector
->getClasses(
95 file_get_contents( $inputPath )
98 $shortpath = substr( $inputPath, $len );
99 $this->classes
[$shortpath] = $result;
104 * @param string $dir Path to a directory to recursively search
105 * for php files with either .php or .inc extensions
107 public function readDir( $dir ) {
108 $it = new RecursiveDirectoryIterator(
109 self
::normalizePathSeparator( realpath( $dir ) ) );
110 $it = new RecursiveIteratorIterator( $it );
112 foreach ( $it as $path => $file ) {
113 $ext = pathinfo( $path, PATHINFO_EXTENSION
);
114 // some older files in mw use .inc
115 if ( $ext === 'php' ||
$ext === 'inc' ) {
116 $this->readFile( $path );
122 * Updates the AutoloadClasses field at the given
125 * @param {string} $filename Filename of JSON
126 * extension/skin registration file
128 protected function generateJsonAutoload( $filename ) {
129 require_once __DIR__
. '/../../includes/json/FormatJson.php';
130 $key = 'AutoloadClasses';
131 $json = FormatJson
::decode( file_get_contents( $filename ), true );
132 unset( $json[$key] );
133 // Inverting the key-value pairs so that they become of the
134 // format class-name : path when they get converted into json.
135 foreach ( $this->classes
as $path => $contained ) {
136 foreach ( $contained as $fqcn ) {
138 // Using substr to remove the leading '/'
139 $json[$key][$fqcn] = substr( $path, 1 );
142 foreach ( $this->overrides
as $path => $fqcn ) {
144 // Using substr to remove the leading '/'
145 $json[$key][$fqcn] = substr( $path, 1 );
148 // Sorting the list of autoload classes.
149 ksort( $json[$key] );
151 // Update file, using constants for the required
153 file_put_contents( $filename,
154 FormatJson
::encode( $json, true ) . "\n" );
158 * Generates a PHP file setting up autoload information.
160 * @param {string} $commandName Command name to include in comment
161 * @param {string} $filename of PHP file to put autoload information in.
163 protected function generatePHPAutoload( $commandName, $filename ) {
164 // No existing JSON file found; update/generate PHP file
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(
175 var_export( $fqcn, true ),
181 foreach ( $this->overrides
as $fqcn => $path ) {
182 $content[$fqcn] = sprintf(
184 var_export( $fqcn, true ),
185 var_export( $path, true )
189 // sort for stable output
192 // extensions using this generator are appending to the existing
194 if ( $this->variableName
=== 'wgAutoloadClasses' ) {
200 $output = implode( "\n\t", $content );
205 // This file is generated by $commandName, do not adjust manually
206 // @codingStandardsIgnoreFile
207 global \${$this->variableName};
209 \${$this->variableName} {$op} [
219 * Write out all known classes to autoload.php, extension.json, or skin.json in
220 * the provided basedir
222 * @param string $commandName Value used in file comment to direct
223 * developers towards the appropriate way to update the autoload.
225 public function generateAutoload( $commandName = 'AutoloadGenerator' ) {
227 // We need to check whether an extenson.json or skin.json exists or not, and
228 // incase it doesn't, update the autoload.php file.
230 $jsonFilename = null;
231 if ( file_exists( $this->basepath
. "/extension.json" ) ) {
232 $jsonFilename = $this->basepath
. "/extension.json";
233 } elseif ( file_exists( $this->basepath
. "/skin.json" ) ) {
234 $jsonFilename = $this->basepath
. "/skin.json";
237 if ( $jsonFilename !== null ) {
238 $this->generateJsonAutoload( $jsonFilename );
240 $this->generatePHPAutoload( $commandName, $this->basepath
. '/autoload.php' );
244 * Ensure that Unix-style path separators ("/") are used in the path.
246 * @param string $path
249 protected static function normalizePathSeparator( $path ) {
250 return str_replace( '\\', '/', $path );
255 * Reads PHP code and returns the FQCN of every class defined within it.
257 class ClassCollector
{
260 * @var string Current namespace
262 protected $namespace = '';
265 * @var array List of FQCN detected in this pass
270 * @var array Token from token_get_all() that started an expect sequence
272 protected $startToken;
275 * @var array List of tokens that are members of the current expect sequence
280 * @var string $code PHP code (including <?php) to detect class names from
281 * @return array List of FQCN detected within the tokens
283 public function getClasses( $code ) {
284 $this->namespace = '';
286 $this->startToken
= null;
289 foreach ( token_get_all( $code ) as $token ) {
290 if ( $this->startToken
=== null ) {
291 $this->tryBeginExpect( $token );
293 $this->tryEndExpect( $token );
297 return $this->classes
;
301 * Determine if $token begins the next expect sequence.
303 * @param array $token
305 protected function tryBeginExpect( $token ) {
306 if ( is_string( $token ) ) {
309 switch ( $token[0] ) {
315 $this->startToken
= $token;
320 * Accepts the next token in an expect sequence
324 protected function tryEndExpect( $token ) {
325 switch ( $this->startToken
[0] ) {
327 // Skip over T_CLASS after T_DOUBLE_COLON because this is something like
328 // "self::static" which accesses the class name. It doens't define a new class.
329 $this->startToken
= null;
332 if ( $token === ';' ||
$token === '{' ) {
333 $this->namespace = $this->implodeTokens() . '\\';
335 $this->tokens
[] = $token;
342 $this->tokens
[] = $token;
343 if ( is_array( $token ) && $token[0] === T_STRING
) {
344 $this->classes
[] = $this->namespace . $this->implodeTokens();
350 * Returns the string representation of the tokens within the
351 * current expect sequence and resets the sequence.
355 protected function implodeTokens() {
357 foreach ( $this->tokens
as $token ) {
358 $content[] = is_string( $token ) ?
$token : $token[1];
362 $this->startToken
= null;
364 return trim( implode( '', $content ), " \n\t" );