MediaWiki master
AutoloadGenerator.php
Go to the documentation of this file.
1<?php
22
37 private const FILETYPE_JSON = 'json';
38 private const FILETYPE_PHP = 'php';
39
43 protected $basepath;
44
48 protected $collector;
49
53 protected $classes = [];
54
58 protected $variableName = 'wgAutoloadClasses';
59
63 protected $overrides = [];
64
70 protected $excludePaths = [];
71
77 protected $psr4Namespaces = [];
78
86 public function __construct( $basepath, $flags = [] ) {
87 if ( !is_array( $flags ) ) {
88 $flags = [ $flags ];
89 }
90 $this->basepath = self::normalizePathSeparator( realpath( $basepath ) );
91 $this->collector = new ClassCollector;
92 if ( in_array( 'local', $flags ) ) {
93 $this->variableName = 'wgAutoloadLocalClasses';
94 }
95 }
96
103 public function setExcludePaths( array $paths ) {
104 foreach ( $paths as $path ) {
105 $this->excludePaths[] = self::normalizePathSeparator( $path );
106 }
107 }
108
117 public function setPsr4Namespaces( array $namespaces ) {
118 foreach ( $namespaces as $ns => $path ) {
119 $ns = rtrim( $ns, '\\' ) . '\\';
120 $this->psr4Namespaces[$ns] = rtrim( self::normalizePathSeparator( $path ), '/' );
121 }
122 }
123
130 private function shouldExclude( $path ) {
131 foreach ( $this->excludePaths as $dir ) {
132 if ( str_starts_with( $path, $dir ) ) {
133 return true;
134 }
135 }
136
137 return false;
138 }
139
148 public function forceClassPath( $fqcn, $inputPath ) {
149 $path = self::normalizePathSeparator( realpath( $inputPath ) );
150 if ( !$path ) {
151 throw new InvalidArgumentException( "Invalid path: $inputPath" );
152 }
153 if ( !str_starts_with( $path, $this->basepath ) ) {
154 throw new InvalidArgumentException( "Path is not within basepath: $inputPath" );
155 }
156 $shortpath = substr( $path, strlen( $this->basepath ) );
157 $this->overrides[$fqcn] = $shortpath;
158 }
159
164 public function readFile( $inputPath ) {
165 // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
166 // reasonable for LocalSettings.php and similar files to be symlinks
167 // to files that are outside of $this->basepath.
168 $inputPath = self::normalizePathSeparator( $inputPath );
169 $len = strlen( $this->basepath );
170 if ( !str_starts_with( $inputPath, $this->basepath ) ) {
171 throw new InvalidArgumentException( "Path is not within basepath: $inputPath" );
172 }
173 if ( $this->shouldExclude( $inputPath ) ) {
174 return;
175 }
176 $fileContents = file_get_contents( $inputPath );
177
178 // Skip files that declare themselves excluded
179 if ( preg_match( '!^// *NO_AUTOLOAD!m', $fileContents ) ) {
180 return;
181 }
182 // Skip files that use CommandLineInc since these execute file-scope
183 // code when included
184 if ( preg_match(
185 '/(require|require_once)[ (].*(CommandLineInc.php|commandLine.inc)/',
186 $fileContents )
187 ) {
188 return;
189 }
190
191 $result = $this->collector->getClasses( $fileContents );
192
193 if ( $result ) {
194 $shortpath = substr( $inputPath, $len );
195 $this->classes[$shortpath] = $result;
196 }
197 }
198
202 public function readDir( $dir ) {
203 $it = new RecursiveDirectoryIterator(
204 self::normalizePathSeparator( realpath( $dir ) ) );
205 $it = new RecursiveIteratorIterator( $it );
206
207 foreach ( $it as $path => $file ) {
208 if ( pathinfo( $path, PATHINFO_EXTENSION ) === 'php' ) {
209 $this->readFile( $path );
210 }
211 }
212 }
213
222 protected function generateJsonAutoload( $filename ) {
223 $key = 'AutoloadClasses';
224 $json = FormatJson::decode( file_get_contents( $filename ), true );
225 unset( $json[$key] );
226 // Inverting the key-value pairs so that they become of the
227 // format class-name : path when they get converted into json.
228 foreach ( $this->classes as $path => $contained ) {
229 foreach ( $contained as $fqcn ) {
230 // Using substr to remove the leading '/'
231 $json[$key][$fqcn] = substr( $path, 1 );
232 }
233 }
234 foreach ( $this->overrides as $path => $fqcn ) {
235 // Using substr to remove the leading '/'
236 $json[$key][$fqcn] = substr( $path, 1 );
237 }
238
239 // Sorting the list of autoload classes.
240 ksort( $json[$key] );
241
242 // Return the whole JSON file
243 return FormatJson::encode( $json, "\t", FormatJson::ALL_OK ) . "\n";
244 }
245
253 protected function generatePHPAutoload( $commandName, $filename ) {
254 // No existing JSON file found; update/generate PHP file
255 $content = [];
256
257 // We need to generate a line each rather than exporting the
258 // full array so __DIR__ can be prepended to all the paths
259 $format = "%s => __DIR__ . %s,";
260 foreach ( $this->classes as $path => $contained ) {
261 $exportedPath = var_export( $path, true );
262 foreach ( $contained as $fqcn ) {
263 $content[$fqcn] = sprintf(
264 $format,
265 var_export( $fqcn, true ),
266 $exportedPath
267 );
268 }
269 }
270
271 foreach ( $this->overrides as $fqcn => $path ) {
272 $content[$fqcn] = sprintf(
273 $format,
274 var_export( $fqcn, true ),
275 var_export( $path, true )
276 );
277 }
278
279 // sort for stable output
280 ksort( $content );
281
282 // extensions using this generator are appending to the existing
283 // autoload.
284 if ( $this->variableName === 'wgAutoloadClasses' ) {
285 $op = '+=';
286 } else {
287 $op = '=';
288 }
289
290 $output = implode( "\n\t", $content );
291 return <<<EOD
292<?php
293// This file is generated by $commandName, do not adjust manually
294// phpcs:disable Generic.Files.LineLength
295global \${$this->variableName};
296
297\${$this->variableName} {$op} [
298 {$output}
299];
300
301EOD;
302 }
303
312 public function getAutoload( $commandName = 'AutoloadGenerator' ) {
313 // We need to check whether an extension.json or skin.json exists or not, and
314 // incase it doesn't, update the autoload.php file.
315
316 $fileinfo = $this->getTargetFileinfo();
317
318 if ( $fileinfo['type'] === self::FILETYPE_JSON ) {
319 return $this->generateJsonAutoload( $fileinfo['filename'] );
320 }
321
322 return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
323 }
324
333 public function getTargetFileinfo() {
334 if ( file_exists( $this->basepath . '/extension.json' ) ) {
335 return [
336 'filename' => $this->basepath . '/extension.json',
337 'type' => self::FILETYPE_JSON
338 ];
339 }
340 if ( file_exists( $this->basepath . '/skin.json' ) ) {
341 return [
342 'filename' => $this->basepath . '/skin.json',
343 'type' => self::FILETYPE_JSON
344 ];
345 }
346
347 return [
348 'filename' => $this->basepath . '/autoload.php',
349 'type' => self::FILETYPE_PHP
350 ];
351 }
352
359 protected static function normalizePathSeparator( $path ) {
360 return str_replace( '\\', '/', $path );
361 }
362
372 public function initMediaWikiDefault() {
373 foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
374 $this->readDir( $this->basepath . '/' . $dir );
375 }
376 foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
377 $this->readFile( $file );
378 }
379 }
380}
Accepts a list of files and directories to search for php files and generates $wgAutoloadLocalClasses...
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)
Reads PHP code and returns the FQCN of every class defined within it.
JSON formatter wrapper class.