MediaWiki REL1_34
AutoloadGenerator.php
Go to the documentation of this file.
1<?php
35 const FILETYPE_JSON = 'json';
36 const FILETYPE_PHP = 'php';
37
41 protected $basepath;
42
46 protected $collector;
47
51 protected $classes = [];
52
56 protected $variableName = 'wgAutoloadClasses';
57
61 protected $overrides = [];
62
68 protected $excludePaths = [];
69
75 protected $psr4Namespaces = [];
76
84 public function __construct( $basepath, $flags = [] ) {
85 if ( !is_array( $flags ) ) {
86 $flags = [ $flags ];
87 }
88 $this->basepath = self::normalizePathSeparator( realpath( $basepath ) );
89 $this->collector = new ClassCollector;
90 if ( in_array( 'local', $flags ) ) {
91 $this->variableName = 'wgAutoloadLocalClasses';
92 }
93 }
94
101 public function setExcludePaths( array $paths ) {
102 foreach ( $paths as $path ) {
103 $this->excludePaths[] = self::normalizePathSeparator( $path );
104 }
105 }
106
116 public function setPsr4Namespaces( array $namespaces ) {
117 foreach ( $namespaces as $ns => $path ) {
118 $ns = rtrim( $ns, '\\' ) . '\\';
119 $this->psr4Namespaces[$ns] = rtrim( self::normalizePathSeparator( $path ), '/' );
120 }
121 }
122
129 private function shouldExclude( $path ) {
130 foreach ( $this->excludePaths as $dir ) {
131 if ( strpos( $path, $dir ) === 0 ) {
132 return true;
133 }
134 }
135
136 return false;
137 }
138
147 public function forceClassPath( $fqcn, $inputPath ) {
148 $path = self::normalizePathSeparator( realpath( $inputPath ) );
149 if ( !$path ) {
150 throw new \Exception( "Invalid path: $inputPath" );
151 }
152 $len = strlen( $this->basepath );
153 if ( substr( $path, 0, $len ) !== $this->basepath ) {
154 throw new \Exception( "Path is not within basepath: $inputPath" );
155 }
156 $shortpath = substr( $path, $len );
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 similiar 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 ( substr( $inputPath, 0, $len ) !== $this->basepath ) {
171 throw new \Exception( "Path is not within basepath: $inputPath" );
172 }
173 if ( $this->shouldExclude( $inputPath ) ) {
174 return;
175 }
176 $result = $this->collector->getClasses(
177 file_get_contents( $inputPath )
178 );
179
180 // Filter out classes that will be found by PSR4
181 $result = array_filter( $result, function ( $class ) use ( $inputPath ) {
182 $parts = explode( '\\', $class );
183 for ( $i = count( $parts ) - 1; $i > 0; $i-- ) {
184 $ns = implode( '\\', array_slice( $parts, 0, $i ) ) . '\\';
185 if ( isset( $this->psr4Namespaces[$ns] ) ) {
186 $expectedPath = $this->psr4Namespaces[$ns] . '/'
187 . implode( '/', array_slice( $parts, $i ) )
188 . '.php';
189 if ( $inputPath === $expectedPath ) {
190 return false;
191 }
192 }
193 }
194
195 return true;
196 } );
197
198 if ( $result ) {
199 $shortpath = substr( $inputPath, $len );
200 $this->classes[$shortpath] = $result;
201 }
202 }
203
208 public function readDir( $dir ) {
209 $it = new RecursiveDirectoryIterator(
210 self::normalizePathSeparator( realpath( $dir ) ) );
211 $it = new RecursiveIteratorIterator( $it );
212
213 foreach ( $it as $path => $file ) {
214 $ext = pathinfo( $path, PATHINFO_EXTENSION );
215 // some older files in mw use .inc
216 if ( $ext === 'php' || $ext === 'inc' ) {
217 $this->readFile( $path );
218 }
219 }
220 }
221
230 protected function generateJsonAutoload( $filename ) {
231 $key = 'AutoloadClasses';
232 $json = FormatJson::decode( file_get_contents( $filename ), true );
233 unset( $json[$key] );
234 // Inverting the key-value pairs so that they become of the
235 // format class-name : path when they get converted into json.
236 foreach ( $this->classes as $path => $contained ) {
237 foreach ( $contained as $fqcn ) {
238 // Using substr to remove the leading '/'
239 $json[$key][$fqcn] = substr( $path, 1 );
240 }
241 }
242 foreach ( $this->overrides as $path => $fqcn ) {
243 // Using substr to remove the leading '/'
244 $json[$key][$fqcn] = substr( $path, 1 );
245 }
246
247 // Sorting the list of autoload classes.
248 ksort( $json[$key] );
249
250 // Return the whole JSON file
251 return FormatJson::encode( $json, "\t", FormatJson::ALL_OK ) . "\n";
252 }
253
261 protected function generatePHPAutoload( $commandName, $filename ) {
262 // No existing JSON file found; update/generate PHP file
263 $content = [];
264
265 // We need to generate a line each rather than exporting the
266 // full array so __DIR__ can be prepended to all the paths
267 $format = "%s => __DIR__ . %s,";
268 foreach ( $this->classes as $path => $contained ) {
269 $exportedPath = var_export( $path, true );
270 foreach ( $contained as $fqcn ) {
271 $content[$fqcn] = sprintf(
272 $format,
273 var_export( $fqcn, true ),
274 $exportedPath
275 );
276 }
277 }
278
279 foreach ( $this->overrides as $fqcn => $path ) {
280 $content[$fqcn] = sprintf(
281 $format,
282 var_export( $fqcn, true ),
283 var_export( $path, true )
284 );
285 }
286
287 // sort for stable output
288 ksort( $content );
289
290 // extensions using this generator are appending to the existing
291 // autoload.
292 if ( $this->variableName === 'wgAutoloadClasses' ) {
293 $op = '+=';
294 } else {
295 $op = '=';
296 }
297
298 $output = implode( "\n\t", $content );
299 return <<<EOD
300<?php
301// This file is generated by $commandName, do not adjust manually
302// phpcs:disable Generic.Files.LineLength
303global \${$this->variableName};
304
305\${$this->variableName} {$op} [
306 {$output}
307];
308
309EOD;
310 }
311
320 public function getAutoload( $commandName = 'AutoloadGenerator' ) {
321 // We need to check whether an extension.json or skin.json exists or not, and
322 // incase it doesn't, update the autoload.php file.
323
324 $fileinfo = $this->getTargetFileinfo();
325
326 if ( $fileinfo['type'] === self::FILETYPE_JSON ) {
327 return $this->generateJsonAutoload( $fileinfo['filename'] );
328 } else {
329 return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
330 }
331 }
332
341 public function getTargetFileinfo() {
342 $fileinfo = [
343 'filename' => $this->basepath . '/autoload.php',
344 'type' => self::FILETYPE_PHP
345 ];
346 if ( file_exists( $this->basepath . '/extension.json' ) ) {
347 $fileinfo = [
348 'filename' => $this->basepath . '/extension.json',
349 'type' => self::FILETYPE_JSON
350 ];
351 } elseif ( file_exists( $this->basepath . '/skin.json' ) ) {
352 $fileinfo = [
353 'filename' => $this->basepath . '/skin.json',
354 'type' => self::FILETYPE_JSON
355 ];
356 }
357
358 return $fileinfo;
359 }
360
367 protected static function normalizePathSeparator( $path ) {
368 return str_replace( '\\', '/', $path );
369 }
370
380 public function initMediaWikiDefault() {
381 foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
382 $this->readDir( $this->basepath . '/' . $dir );
383 }
384 foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
385 $this->readFile( $file );
386 }
387 }
388}
Accepts a list of files and directories to search for php files and generates $wgAutoloadLocalClasses...
shouldExclude( $path)
Whether the file should be excluded.
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)
Set PSR4 namespaces.
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.
$content
Definition router.php:78
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42
if(!is_readable( $file)) $ext
Definition router.php:48