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  $len = strlen( $this->basepath );
151  if ( substr( $path, 0, $len ) !== $this->basepath ) {
152  throw new \Exception( "Path is not within basepath: $inputPath" );
153  }
154  $shortpath = substr( $path, $len );
155  $this->overrides[$fqcn] = $shortpath;
156  }
157 
162  public function readFile( $inputPath ) {
163  // NOTE: do NOT expand $inputPath using realpath(). It is perfectly
164  // reasonable for LocalSettings.php and similiar files to be symlinks
165  // to files that are outside of $this->basepath.
166  $inputPath = self::normalizePathSeparator( $inputPath );
167  $len = strlen( $this->basepath );
168  if ( substr( $inputPath, 0, $len ) !== $this->basepath ) {
169  throw new \Exception( "Path is not within basepath: $inputPath" );
170  }
171  if ( $this->shouldExclude( $inputPath ) ) {
172  return;
173  }
174  $fileContents = file_get_contents( $inputPath );
175 
176  // Skip files that declare themselves excluded
177  if ( preg_match( '!^// *NO_AUTOLOAD!m', $fileContents ) ) {
178  return;
179  }
180  // Skip files that use CommandLineInc since these execute file-scope
181  // code when included
182  if ( preg_match(
183  '/(require|require_once)[ (].*(CommandLineInc.php|commandLine.inc)/',
184  $fileContents )
185  ) {
186  return;
187  }
188 
189  $result = $this->collector->getClasses( $fileContents );
190 
191  // Filter out classes that will be found by PSR4
192  $result = array_filter( $result, function ( $class ) use ( $inputPath ) {
193  $parts = explode( '\\', $class );
194  for ( $i = count( $parts ) - 1; $i > 0; $i-- ) {
195  $ns = implode( '\\', array_slice( $parts, 0, $i ) ) . '\\';
196  if ( isset( $this->psr4Namespaces[$ns] ) ) {
197  $expectedPath = $this->psr4Namespaces[$ns] . '/'
198  . implode( '/', array_slice( $parts, $i ) )
199  . '.php';
200  if ( $inputPath === $expectedPath ) {
201  return false;
202  }
203  }
204  }
205 
206  return true;
207  } );
208 
209  if ( $result ) {
210  $shortpath = substr( $inputPath, $len );
211  $this->classes[$shortpath] = $result;
212  }
213  }
214 
218  public function readDir( $dir ) {
219  $it = new RecursiveDirectoryIterator(
220  self::normalizePathSeparator( realpath( $dir ) ) );
221  $it = new RecursiveIteratorIterator( $it );
222 
223  foreach ( $it as $path => $file ) {
224  if ( pathinfo( $path, PATHINFO_EXTENSION ) === 'php' ) {
225  $this->readFile( $path );
226  }
227  }
228  }
229 
238  protected function generateJsonAutoload( $filename ) {
239  $key = 'AutoloadClasses';
240  $json = FormatJson::decode( file_get_contents( $filename ), true );
241  unset( $json[$key] );
242  // Inverting the key-value pairs so that they become of the
243  // format class-name : path when they get converted into json.
244  foreach ( $this->classes as $path => $contained ) {
245  foreach ( $contained as $fqcn ) {
246  // Using substr to remove the leading '/'
247  $json[$key][$fqcn] = substr( $path, 1 );
248  }
249  }
250  foreach ( $this->overrides as $path => $fqcn ) {
251  // Using substr to remove the leading '/'
252  $json[$key][$fqcn] = substr( $path, 1 );
253  }
254 
255  // Sorting the list of autoload classes.
256  ksort( $json[$key] );
257 
258  // Return the whole JSON file
259  return FormatJson::encode( $json, "\t", FormatJson::ALL_OK ) . "\n";
260  }
261 
269  protected function generatePHPAutoload( $commandName, $filename ) {
270  // No existing JSON file found; update/generate PHP file
271  $content = [];
272 
273  // We need to generate a line each rather than exporting the
274  // full array so __DIR__ can be prepended to all the paths
275  $format = "%s => __DIR__ . %s,";
276  foreach ( $this->classes as $path => $contained ) {
277  $exportedPath = var_export( $path, true );
278  foreach ( $contained as $fqcn ) {
279  $content[$fqcn] = sprintf(
280  $format,
281  var_export( $fqcn, true ),
282  $exportedPath
283  );
284  }
285  }
286 
287  foreach ( $this->overrides as $fqcn => $path ) {
288  $content[$fqcn] = sprintf(
289  $format,
290  var_export( $fqcn, true ),
291  var_export( $path, true )
292  );
293  }
294 
295  // sort for stable output
296  ksort( $content );
297 
298  // extensions using this generator are appending to the existing
299  // autoload.
300  if ( $this->variableName === 'wgAutoloadClasses' ) {
301  $op = '+=';
302  } else {
303  $op = '=';
304  }
305 
306  $output = implode( "\n\t", $content );
307  return <<<EOD
308 <?php
309 // This file is generated by $commandName, do not adjust manually
310 // phpcs:disable Generic.Files.LineLength
311 global \${$this->variableName};
312 
313 \${$this->variableName} {$op} [
314  {$output}
315 ];
316 
317 EOD;
318  }
319 
328  public function getAutoload( $commandName = 'AutoloadGenerator' ) {
329  // We need to check whether an extension.json or skin.json exists or not, and
330  // incase it doesn't, update the autoload.php file.
331 
332  $fileinfo = $this->getTargetFileinfo();
333 
334  if ( $fileinfo['type'] === self::FILETYPE_JSON ) {
335  return $this->generateJsonAutoload( $fileinfo['filename'] );
336  }
337 
338  return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
339  }
340 
349  public function getTargetFileinfo() {
350  if ( file_exists( $this->basepath . '/extension.json' ) ) {
351  return [
352  'filename' => $this->basepath . '/extension.json',
353  'type' => self::FILETYPE_JSON
354  ];
355  }
356  if ( file_exists( $this->basepath . '/skin.json' ) ) {
357  return [
358  'filename' => $this->basepath . '/skin.json',
359  'type' => self::FILETYPE_JSON
360  ];
361  }
362 
363  return [
364  'filename' => $this->basepath . '/autoload.php',
365  'type' => self::FILETYPE_PHP
366  ];
367  }
368 
375  protected static function normalizePathSeparator( $path ) {
376  return str_replace( '\\', '/', $path );
377  }
378 
388  public function initMediaWikiDefault() {
389  foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
390  $this->readDir( $this->basepath . '/' . $dir );
391  }
392  foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
393  $this->readFile( $file );
394  }
395  }
396 }
AutoloadGenerator\setPsr4Namespaces
setPsr4Namespaces(array $namespaces)
Unlike self::setExcludePaths(), this will only skip outputting the autoloader entry when the namespac...
Definition: AutoloadGenerator.php:114
AutoloadGenerator\initMediaWikiDefault
initMediaWikiDefault()
Initialize the source files and directories which are used for the MediaWiki default autoloader in {m...
Definition: AutoloadGenerator.php:388
AutoloadGenerator\forceClassPath
forceClassPath( $fqcn, $inputPath)
Force a class to be autoloaded from a specific path, regardless of where or if it was detected.
Definition: AutoloadGenerator.php:145
AutoloadGenerator\normalizePathSeparator
static normalizePathSeparator( $path)
Ensure that Unix-style path separators ("/") are used in the path.
Definition: AutoloadGenerator.php:375
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
AutoloadGenerator\readDir
readDir( $dir)
Definition: AutoloadGenerator.php:218
AutoloadGenerator
Accepts a list of files and directories to search for php files and generates $wgAutoloadLocalClasses...
Definition: AutoloadGenerator.php:34
AutoloadGenerator\$variableName
string $variableName
The global variable to write output to.
Definition: AutoloadGenerator.php:56
ClassCollector
Reads PHP code and returns the FQCN of every class defined within it.
Definition: ClassCollector.php:24
FormatJson\ALL_OK
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
AutoloadGenerator\readFile
readFile( $inputPath)
Definition: AutoloadGenerator.php:162
AutoloadGenerator\shouldExclude
shouldExclude( $path)
Whether the file should be excluded.
Definition: AutoloadGenerator.php:127
AutoloadGenerator\$classes
array $classes
Map of file shortpath to list of FQCN detected within file.
Definition: AutoloadGenerator.php:51
FormatJson\decode
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:174
FormatJson\encode
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:115
AutoloadGenerator\setExcludePaths
setExcludePaths(array $paths)
Directories that should be excluded.
Definition: AutoloadGenerator.php:101
AutoloadGenerator\$overrides
array $overrides
Map of FQCN to relative path(from self::$basepath)
Definition: AutoloadGenerator.php:61
AutoloadGenerator\__construct
__construct( $basepath, $flags=[])
Definition: AutoloadGenerator.php:84
AutoloadGenerator\$psr4Namespaces
string[] $psr4Namespaces
Configured PSR4 namespaces.
Definition: AutoloadGenerator.php:75
AutoloadGenerator\$excludePaths
string[] $excludePaths
Directories that should be excluded.
Definition: AutoloadGenerator.php:68
AutoloadGenerator\FILETYPE_PHP
const FILETYPE_PHP
Definition: AutoloadGenerator.php:36
$content
$content
Definition: router.php:76
AutoloadGenerator\generateJsonAutoload
generateJsonAutoload( $filename)
Updates the AutoloadClasses field at the given filename.
Definition: AutoloadGenerator.php:238
AutoloadGenerator\getAutoload
getAutoload( $commandName='AutoloadGenerator')
Returns all known classes as a string, which can be used to put into a target file (e....
Definition: AutoloadGenerator.php:328
AutoloadGenerator\$basepath
string $basepath
Root path of the project being scanned for classes.
Definition: AutoloadGenerator.php:41
AutoloadGenerator\generatePHPAutoload
generatePHPAutoload( $commandName, $filename)
Generates a PHP file setting up autoload information.
Definition: AutoloadGenerator.php:269
$path
$path
Definition: NoLocalSettings.php:25
AutoloadGenerator\getTargetFileinfo
getTargetFileinfo()
Returns the filename of the extension.json of skin.json, if there's any, or otherwise the path to the...
Definition: AutoloadGenerator.php:349
AutoloadGenerator\FILETYPE_JSON
const FILETYPE_JSON
Definition: AutoloadGenerator.php:35
$fileinfo
$fileinfo
Definition: generateLocalAutoload.php:18
AutoloadGenerator\$collector
ClassCollector $collector
Helper class extracts class names from php files.
Definition: AutoloadGenerator.php:46