MediaWiki  master
AutoloadGenerator.php
Go to the documentation of this file.
1 <?php
35  private const FILETYPE_JSON = 'json';
36  private 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 
114  public function setPsr4Namespaces( array $namespaces ) {
115  foreach ( $namespaces as $ns => $path ) {
116  $ns = rtrim( $ns, '\\' ) . '\\';
117  $this->psr4Namespaces[$ns] = rtrim( self::normalizePathSeparator( $path ), '/' );
118  }
119  }
120 
127  private function shouldExclude( $path ) {
128  foreach ( $this->excludePaths as $dir ) {
129  if ( strpos( $path, $dir ) === 0 ) {
130  return true;
131  }
132  }
133 
134  return false;
135  }
136 
145  public function forceClassPath( $fqcn, $inputPath ) {
146  $path = self::normalizePathSeparator( realpath( $inputPath ) );
147  if ( !$path ) {
148  throw new \Exception( "Invalid path: $inputPath" );
149  }
150  if ( !str_starts_with( $path, $this->basepath ) ) {
151  throw new \Exception( "Path is not within basepath: $inputPath" );
152  }
153  $shortpath = substr( $path, strlen( $this->basepath ) );
154  $this->overrides[$fqcn] = $shortpath;
155  }
156 
161  public function readFile( $inputPath ) {
162  // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
163  // reasonable for LocalSettings.php and similar files to be symlinks
164  // to files that are outside of $this->basepath.
165  $inputPath = self::normalizePathSeparator( $inputPath );
166  $len = strlen( $this->basepath );
167  if ( !str_starts_with( $inputPath, $this->basepath ) ) {
168  throw new \Exception( "Path is not within basepath: $inputPath" );
169  }
170  if ( $this->shouldExclude( $inputPath ) ) {
171  return;
172  }
173  $fileContents = file_get_contents( $inputPath );
174 
175  // Skip files that declare themselves excluded
176  if ( preg_match( '!^// *NO_AUTOLOAD!m', $fileContents ) ) {
177  return;
178  }
179  // Skip files that use CommandLineInc since these execute file-scope
180  // code when included
181  if ( preg_match(
182  '/(require|require_once)[ (].*(CommandLineInc.php|commandLine.inc)/',
183  $fileContents )
184  ) {
185  return;
186  }
187 
188  $result = $this->collector->getClasses( $fileContents );
189 
190  // Filter out classes that will be found by PSR4
191  $result = array_filter( $result, function ( $class ) use ( $inputPath ) {
192  $parts = explode( '\\', $class );
193  for ( $i = count( $parts ) - 1; $i > 0; $i-- ) {
194  $ns = implode( '\\', array_slice( $parts, 0, $i ) ) . '\\';
195  if ( isset( $this->psr4Namespaces[$ns] ) ) {
196  $expectedPath = $this->psr4Namespaces[$ns] . '/'
197  . implode( '/', array_slice( $parts, $i ) )
198  . '.php';
199  if ( $inputPath === $expectedPath ) {
200  return false;
201  }
202  }
203  }
204 
205  return true;
206  } );
207 
208  if ( $result ) {
209  $shortpath = substr( $inputPath, $len );
210  $this->classes[$shortpath] = $result;
211  }
212  }
213 
217  public function readDir( $dir ) {
218  $it = new RecursiveDirectoryIterator(
219  self::normalizePathSeparator( realpath( $dir ) ) );
220  $it = new RecursiveIteratorIterator( $it );
221 
222  foreach ( $it as $path => $file ) {
223  if ( pathinfo( $path, PATHINFO_EXTENSION ) === 'php' ) {
224  $this->readFile( $path );
225  }
226  }
227  }
228 
237  protected function generateJsonAutoload( $filename ) {
238  $key = 'AutoloadClasses';
239  $json = FormatJson::decode( file_get_contents( $filename ), true );
240  unset( $json[$key] );
241  // Inverting the key-value pairs so that they become of the
242  // format class-name : path when they get converted into json.
243  foreach ( $this->classes as $path => $contained ) {
244  foreach ( $contained as $fqcn ) {
245  // Using substr to remove the leading '/'
246  $json[$key][$fqcn] = substr( $path, 1 );
247  }
248  }
249  foreach ( $this->overrides as $path => $fqcn ) {
250  // Using substr to remove the leading '/'
251  $json[$key][$fqcn] = substr( $path, 1 );
252  }
253 
254  // Sorting the list of autoload classes.
255  ksort( $json[$key] );
256 
257  // Return the whole JSON file
258  return FormatJson::encode( $json, "\t", FormatJson::ALL_OK ) . "\n";
259  }
260 
268  protected function generatePHPAutoload( $commandName, $filename ) {
269  // No existing JSON file found; update/generate PHP file
270  $content = [];
271 
272  // We need to generate a line each rather than exporting the
273  // full array so __DIR__ can be prepended to all the paths
274  $format = "%s => __DIR__ . %s,";
275  foreach ( $this->classes as $path => $contained ) {
276  $exportedPath = var_export( $path, true );
277  foreach ( $contained as $fqcn ) {
278  $content[$fqcn] = sprintf(
279  $format,
280  var_export( $fqcn, true ),
281  $exportedPath
282  );
283  }
284  }
285 
286  foreach ( $this->overrides as $fqcn => $path ) {
287  $content[$fqcn] = sprintf(
288  $format,
289  var_export( $fqcn, true ),
290  var_export( $path, true )
291  );
292  }
293 
294  // sort for stable output
295  ksort( $content );
296 
297  // extensions using this generator are appending to the existing
298  // autoload.
299  if ( $this->variableName === 'wgAutoloadClasses' ) {
300  $op = '+=';
301  } else {
302  $op = '=';
303  }
304 
305  $output = implode( "\n\t", $content );
306  return <<<EOD
307 <?php
308 // This file is generated by $commandName, do not adjust manually
309 // phpcs:disable Generic.Files.LineLength
310 global \${$this->variableName};
311 
312 \${$this->variableName} {$op} [
313  {$output}
314 ];
315 
316 EOD;
317  }
318 
327  public function getAutoload( $commandName = 'AutoloadGenerator' ) {
328  // We need to check whether an extension.json or skin.json exists or not, and
329  // incase it doesn't, update the autoload.php file.
330 
331  $fileinfo = $this->getTargetFileinfo();
332 
333  if ( $fileinfo['type'] === self::FILETYPE_JSON ) {
334  return $this->generateJsonAutoload( $fileinfo['filename'] );
335  }
336 
337  return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
338  }
339 
348  public function getTargetFileinfo() {
349  if ( file_exists( $this->basepath . '/extension.json' ) ) {
350  return [
351  'filename' => $this->basepath . '/extension.json',
352  'type' => self::FILETYPE_JSON
353  ];
354  }
355  if ( file_exists( $this->basepath . '/skin.json' ) ) {
356  return [
357  'filename' => $this->basepath . '/skin.json',
358  'type' => self::FILETYPE_JSON
359  ];
360  }
361 
362  return [
363  'filename' => $this->basepath . '/autoload.php',
364  'type' => self::FILETYPE_PHP
365  ];
366  }
367 
374  protected static function normalizePathSeparator( $path ) {
375  return str_replace( '\\', '/', $path );
376  }
377 
387  public function initMediaWikiDefault() {
388  foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
389  $this->readDir( $this->basepath . '/' . $dir );
390  }
391  foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
392  $this->readFile( $file );
393  }
394  }
395 }
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)
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.
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:96
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:146
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
$content
Definition: router.php:76
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42