MediaWiki master
AutoloadGenerator.php
Go to the documentation of this file.
1<?php
8
29 private const FILETYPE_JSON = 'json';
30 private const FILETYPE_PHP = 'php';
31
35 protected $basepath;
36
40 protected $collector;
41
45 protected $classes = [];
46
50 protected $variableName = 'wgAutoloadClasses';
51
55 protected $overrides = [];
56
62 protected $excludePaths = [];
63
69 protected $psr4Namespaces = [];
70
78 public function __construct( $basepath, $flags = [] ) {
79 if ( !is_array( $flags ) ) {
80 $flags = [ $flags ];
81 }
82 $this->basepath = self::normalizePathSeparator( realpath( $basepath ) );
83 $this->collector = new ClassCollector;
84 if ( in_array( 'local', $flags ) ) {
85 $this->variableName = 'wgAutoloadLocalClasses';
86 }
87 }
88
95 public function setExcludePaths( array $paths ) {
96 foreach ( $paths as $path ) {
97 $this->excludePaths[] = self::normalizePathSeparator( $path );
98 }
99 }
100
109 public function setPsr4Namespaces( array $namespaces ) {
110 wfDeprecated( __METHOD__, '1.40' );
111 foreach ( $namespaces as $ns => $path ) {
112 $ns = rtrim( $ns, '\\' ) . '\\';
113 $this->psr4Namespaces[$ns] = rtrim( self::normalizePathSeparator( $path ), '/' );
114 }
115 }
116
123 private function shouldExclude( $path ) {
124 foreach ( $this->excludePaths as $dir ) {
125 if ( str_starts_with( $path, $dir ) ) {
126 return true;
127 }
128 }
129
130 return false;
131 }
132
141 public function forceClassPath( $fqcn, $inputPath ) {
142 $path = self::normalizePathSeparator( realpath( $inputPath ) );
143 if ( !$path ) {
144 throw new InvalidArgumentException( "Invalid path: $inputPath" );
145 }
146 if ( !str_starts_with( $path, $this->basepath ) ) {
147 throw new InvalidArgumentException( "Path is not within basepath: $inputPath" );
148 }
149 $shortpath = substr( $path, strlen( $this->basepath ) );
150 $this->overrides[$fqcn] = $shortpath;
151 }
152
157 public function readFile( $inputPath ) {
158 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
159 // reasonable for LocalSettings.php and similar files to be symlinks
160 // to files that are outside of $this->basepath.
161 $inputPath = self::normalizePathSeparator( $inputPath );
162 $len = strlen( $this->basepath );
163 if ( !str_starts_with( $inputPath, $this->basepath ) ) {
164 throw new InvalidArgumentException( "Path is not within basepath: $inputPath" );
165 }
166 if ( $this->shouldExclude( $inputPath ) ) {
167 return;
168 }
169 $fileContents = file_get_contents( $inputPath );
170
171 // Skip files that declare themselves excluded
172 if ( preg_match( '!^// *NO_AUTOLOAD!m', $fileContents ) ) {
173 return;
174 }
175 // Skip files that use CommandLineInc since these execute file-scope
176 // code when included
177 if ( preg_match(
178 '/(require|require_once)[ (].*(CommandLineInc.php|commandLine.inc)/',
179 $fileContents )
180 ) {
181 return;
182 }
183
184 $result = $this->collector->getClasses( $fileContents );
185
186 if ( $result ) {
187 $shortpath = substr( $inputPath, $len );
188 $this->classes[$shortpath] = $result;
189 }
190 }
191
195 public function readDir( $dir ) {
196 $it = new RecursiveDirectoryIterator(
197 self::normalizePathSeparator( realpath( $dir ) ) );
198 $it = new RecursiveIteratorIterator( $it );
199
200 foreach ( $it as $path => $file ) {
201 if ( pathinfo( $path, PATHINFO_EXTENSION ) === 'php' ) {
202 $this->readFile( $path );
203 }
204 }
205 }
206
215 protected function generateJsonAutoload( $filename ) {
216 $key = 'AutoloadClasses';
217 $json = FormatJson::decode( file_get_contents( $filename ), true );
218 unset( $json[$key] );
219 // Inverting the key-value pairs so that they become of the
220 // format class-name : path when they get converted into json.
221 foreach ( $this->classes as $path => $contained ) {
222 foreach ( $contained as $fqcn ) {
223 // Using substr to remove the leading '/'
224 $json[$key][$fqcn] = substr( $path, 1 );
225 }
226 }
227 foreach ( $this->overrides as $path => $fqcn ) {
228 // Using substr to remove the leading '/'
229 $json[$key][$fqcn] = substr( $path, 1 );
230 }
231
232 // Sorting the list of autoload classes.
233 ksort( $json[$key] );
234
235 // Return the whole JSON file
236 return FormatJson::encode( $json, "\t", FormatJson::ALL_OK ) . "\n";
237 }
238
246 protected function generatePHPAutoload( $commandName, $filename ) {
247 // No existing JSON file found; update/generate PHP file
248 $content = [];
249
250 // We need to generate a line each rather than exporting the
251 // full array so __DIR__ can be prepended to all the paths
252 $format = "%s => __DIR__ . %s,";
253 foreach ( $this->classes as $path => $contained ) {
254 $exportedPath = var_export( $path, true );
255 foreach ( $contained as $fqcn ) {
256 $content[$fqcn] = sprintf(
257 $format,
258 var_export( $fqcn, true ),
259 $exportedPath
260 );
261 }
262 }
263
264 foreach ( $this->overrides as $fqcn => $path ) {
265 $content[$fqcn] = sprintf(
266 $format,
267 var_export( $fqcn, true ),
268 var_export( $path, true )
269 );
270 }
271
272 // sort for stable output
273 ksort( $content );
274
275 // extensions using this generator are appending to the existing
276 // autoload.
277 if ( $this->variableName === 'wgAutoloadClasses' ) {
278 $op = '+=';
279 } else {
280 $op = '=';
281 }
282
283 $output = implode( "\n\t", $content );
284 return <<<EOD
285<?php
286// This file is generated by $commandName, do not adjust manually
287// phpcs:disable Generic.Files.LineLength
288global \${$this->variableName};
289
290\${$this->variableName} {$op} [
291 {$output}
292];
293
294EOD;
295 }
296
305 public function getAutoload( $commandName = 'AutoloadGenerator' ) {
306 // We need to check whether an extension.json or skin.json exists or not, and
307 // incase it doesn't, update the autoload.php file.
308
309 $fileinfo = $this->getTargetFileinfo();
310
311 if ( $fileinfo['type'] === self::FILETYPE_JSON ) {
312 return $this->generateJsonAutoload( $fileinfo['filename'] );
313 }
314
315 return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
316 }
317
326 public function getTargetFileinfo() {
327 if ( file_exists( $this->basepath . '/extension.json' ) ) {
328 return [
329 'filename' => $this->basepath . '/extension.json',
330 'type' => self::FILETYPE_JSON
331 ];
332 }
333 if ( file_exists( $this->basepath . '/skin.json' ) ) {
334 return [
335 'filename' => $this->basepath . '/skin.json',
336 'type' => self::FILETYPE_JSON
337 ];
338 }
339
340 return [
341 'filename' => $this->basepath . '/autoload.php',
342 'type' => self::FILETYPE_PHP
343 ];
344 }
345
352 protected static function normalizePathSeparator( $path ) {
353 return str_replace( '\\', '/', $path );
354 }
355
365 public function initMediaWikiDefault() {
366 foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
367 $this->readDir( $this->basepath . '/' . $dir );
368 }
369 foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
370 $this->readFile( $file );
371 }
372 }
373}
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that a deprecated feature was used.
Scan given directories and files and create an autoload class map.
string $basepath
Root path of the project being scanned for classes.
setExcludePaths(array $paths)
Directories that should be excluded.
getTargetFileinfo()
Returns the filename of the extension.json of skin.json, if there's any, or otherwise the path to the...
generateJsonAutoload( $filename)
Updates the AutoloadClasses field at the given filename.
string[] $psr4Namespaces
Configured PSR4 namespaces.
__construct( $basepath, $flags=[])
getAutoload( $commandName='AutoloadGenerator')
Returns all known classes as a string, which can be used to put into a target file (e....
forceClassPath( $fqcn, $inputPath)
Force a class to be autoloaded from a specific path, regardless of where or if it was detected.
array $classes
Map of file shortpath to list of FQCN detected within file.
generatePHPAutoload( $commandName, $filename)
Generates a PHP file setting up autoload information.
string $variableName
The global variable to write output to.
initMediaWikiDefault()
Initialize the source files and directories which are used for the MediaWiki default autoloader in {m...
setPsr4Namespaces(array $namespaces)
Unlike self::setExcludePaths(), this will only skip outputting the autoloader entry when the namespac...
ClassCollector $collector
Helper class extracts class names from php files.
string[] $excludePaths
Directories that should be excluded.
static normalizePathSeparator( $path)
Ensure that Unix-style path separators ("/") are used in the path.
array $overrides
Map of FQCN to relative path(from self::$basepath)
Read a PHP file and return the FQCN of every class defined within it.
JSON formatter wrapper class.