Completed
Branch master (467086)
by
unknown
30:56
created

AutoloadGenerator::getTargetFileinfo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 3
eloc 13
nc 3
nop 0
dl 0
loc 19
rs 9.4285
c 1
b 0
f 1
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->generateAutoload();
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
141
				// Using substr to remove the leading '/'
142
				$json[$key][$fqcn] = substr( $path, 1 );
143
			}
144
		}
145
		foreach ( $this->overrides as $path => $fqcn ) {
146
147
			// Using substr to remove the leading '/'
148
			$json[$key][$fqcn] = substr( $path, 1 );
149
		}
150
151
		// Sorting the list of autoload classes.
152
		ksort( $json[$key] );
153
154
		// Return the whole JSON file
155
		return FormatJson::encode( $json, true ) . "\n";
156
	}
157
158
	/**
159
	 * Generates a PHP file setting up autoload information.
160
	 *
161
	 * @param {string} $commandName Command name to include in comment
0 ignored issues
show
Documentation introduced by
The doc-type {string} could not be parsed: Unknown type name "{string}" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
162
	 * @param {string} $filename of PHP file to put autoload information in.
0 ignored issues
show
Documentation introduced by
The doc-type {string} could not be parsed: Unknown type name "{string}" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
163
	 */
164
	protected function generatePHPAutoload( $commandName, $filename ) {
165
		// No existing JSON file found; update/generate PHP file
166
		$content = [];
167
168
		// We need to generate a line each rather than exporting the
169
		// full array so __DIR__ can be prepended to all the paths
170
		$format = "%s => __DIR__ . %s,";
171
		foreach ( $this->classes as $path => $contained ) {
172
			$exportedPath = var_export( $path, true );
173
			foreach ( $contained as $fqcn ) {
174
				$content[$fqcn] = sprintf(
175
					$format,
176
					var_export( $fqcn, true ),
177
					$exportedPath
178
				);
179
			}
180
		}
181
182
		foreach ( $this->overrides as $fqcn => $path ) {
183
			$content[$fqcn] = sprintf(
184
				$format,
185
				var_export( $fqcn, true ),
186
				var_export( $path, true )
187
			);
188
		}
189
190
		// sort for stable output
191
		ksort( $content );
192
193
		// extensions using this generator are appending to the existing
194
		// autoload.
195
		if ( $this->variableName === 'wgAutoloadClasses' ) {
196
			$op = '+=';
197
		} else {
198
			$op = '=';
199
		}
200
201
		$output = implode( "\n\t", $content );
202
		return
203
			<<<EOD
204
<?php
205
// This file is generated by $commandName, do not adjust manually
206
// @codingStandardsIgnoreFile
207
global \${$this->variableName};
208
209
\${$this->variableName} {$op} [
210
	{$output}
211
];
212
213
EOD;
214
215
	}
216
217
	/**
218
	 * Returns all known classes as a string, which can be used to put into a target
219
	 * file (e.g. extension.json, skin.json or autoload.php)
220
	 *
221
	 * @param string $commandName Value used in file comment to direct
222
	 *  developers towards the appropriate way to update the autoload.
223
	 * @return string
224
	 */
225
	public function getAutoload( $commandName = 'AutoloadGenerator' ) {
226
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.
229
230
		$fileinfo = $this->getTargetFileinfo();
231
232
		if ( $fileinfo['type'] === AutoloadGenerator::FILETYPE_JSON ) {
233
			return $this->generateJsonAutoload( $fileinfo['filename'] );
234
		} else {
235
			return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
236
		}
237
	}
238
239
	/**
240
	 * Returns the filename of the extension.json of skin.json, if there's any, or
241
	 * otherwise the path to the autoload.php file in an array as the "filename"
242
	 * key and with the type (AutoloadGenerator::FILETYPE_JSON or AutoloadGenerator::FILETYPE_PHP)
243
	 * of the file as the "type" key.
244
	 *
245
	 * @return array
246
	 */
247
	public function getTargetFileinfo() {
248
		$fileinfo = [
249
			'filename' => $this->basepath . '/autoload.php',
250
			'type' => AutoloadGenerator::FILETYPE_PHP
251
		];
252
		if ( file_exists( $this->basepath . '/extension.json' ) ) {
253
			$fileinfo = [
254
				'filename' => $this->basepath . '/extension.json',
255
				'type' => AutoloadGenerator::FILETYPE_JSON
256
			];
257
		} elseif ( file_exists( $this->basepath . '/skin.json' ) ) {
258
			$fileinfo = [
259
				'filename' => $this->basepath . '/skin.json',
260
				'type' => AutoloadGenerator::FILETYPE_JSON
261
			];
262
		}
263
264
		return $fileinfo;
265
	}
266
267
	/**
268
	 * Ensure that Unix-style path separators ("/") are used in the path.
269
	 *
270
	 * @param string $path
271
	 * @return string
272
	 */
273
	protected static function normalizePathSeparator( $path ) {
274
		return str_replace( '\\', '/', $path );
275
	}
276
277
	/**
278
	 * Initialize the source files and directories which are used for the MediaWiki default
279
	 * autoloader in {mw-base-dir}/autoload.php including:
280
	 *  * includes/
281
	 *  * languages/
282
	 *  * maintenance/
283
	 *  * mw-config/
284
	 *  * /*.php
285
	 */
286
	public function initMediaWikiDefault() {
287
		foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
288
			$this->readDir( $this->basepath . '/' . $dir );
289
		}
290
		foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
291
			$this->readFile( $file );
292
		}
293
	}
294
}
295
296
/**
297
 * Reads PHP code and returns the FQCN of every class defined within it.
298
 */
299
class ClassCollector {
300
301
	/**
302
	 * @var string Current namespace
303
	 */
304
	protected $namespace = '';
305
306
	/**
307
	 * @var array List of FQCN detected in this pass
308
	 */
309
	protected $classes;
310
311
	/**
312
	 * @var array Token from token_get_all() that started an expect sequence
313
	 */
314
	protected $startToken;
315
316
	/**
317
	 * @var array List of tokens that are members of the current expect sequence
318
	 */
319
	protected $tokens;
320
321
	/**
322
	 * @var string $code PHP code (including <?php) to detect class names from
323
	 * @return array List of FQCN detected within the tokens
324
	 */
325
	public function getClasses( $code ) {
326
		$this->namespace = '';
327
		$this->classes = [];
328
		$this->startToken = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $startToken.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
329
		$this->tokens = [];
330
331
		foreach ( token_get_all( $code ) as $token ) {
332
			if ( $this->startToken === null ) {
333
				$this->tryBeginExpect( $token );
334
			} else {
335
				$this->tryEndExpect( $token );
336
			}
337
		}
338
339
		return $this->classes;
340
	}
341
342
	/**
343
	 * Determine if $token begins the next expect sequence.
344
	 *
345
	 * @param array $token
346
	 */
347
	protected function tryBeginExpect( $token ) {
348
		if ( is_string( $token ) ) {
349
			return;
350
		}
351
		switch ( $token[0] ) {
352
		case T_NAMESPACE:
353
		case T_CLASS:
354
		case T_INTERFACE:
355
		case T_TRAIT:
356
		case T_DOUBLE_COLON:
357
			$this->startToken = $token;
358
		}
359
	}
360
361
	/**
362
	 * Accepts the next token in an expect sequence
363
	 *
364
	 * @param array
365
	 */
366
	protected function tryEndExpect( $token ) {
367
		switch ( $this->startToken[0] ) {
368
		case T_DOUBLE_COLON:
369
			// Skip over T_CLASS after T_DOUBLE_COLON because this is something like
370
			// "self::static" which accesses the class name. It doens't define a new class.
371
			$this->startToken = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $startToken.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
372
			break;
373
		case T_NAMESPACE:
374
			if ( $token === ';' || $token === '{' ) {
375
				$this->namespace = $this->implodeTokens() . '\\';
376
			} else {
377
				$this->tokens[] = $token;
378
			}
379
			break;
380
381
		case T_CLASS:
382
		case T_INTERFACE:
383
		case T_TRAIT:
384
			$this->tokens[] = $token;
385
			if ( is_array( $token ) && $token[0] === T_STRING ) {
386
				$this->classes[] = $this->namespace . $this->implodeTokens();
387
			}
388
		}
389
	}
390
391
	/**
392
	 * Returns the string representation of the tokens within the
393
	 * current expect sequence and resets the sequence.
394
	 *
395
	 * @return string
396
	 */
397
	protected function implodeTokens() {
398
		$content = [];
399
		foreach ( $this->tokens as $token ) {
400
			$content[] = is_string( $token ) ? $token : $token[1];
401
		}
402
403
		$this->tokens = [];
404
		$this->startToken = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $startToken.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
405
406
		return trim( implode( '', $content ), " \n\t" );
407
	}
408
}
409