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 
115  public function setPsr4Namespaces( array $namespaces ) {
116  foreach ( $namespaces as $ns => $path ) {
117  $ns = rtrim( $ns, '\\' ) . '\\';
118  $this->psr4Namespaces[$ns] = rtrim( self::normalizePathSeparator( $path ), '/' );
119  }
120  }
121 
128  private function shouldExclude( $path ) {
129  foreach ( $this->excludePaths as $dir ) {
130  if ( str_starts_with( $path, $dir ) ) {
131  return true;
132  }
133  }
134 
135  return false;
136  }
137 
146  public function forceClassPath( $fqcn, $inputPath ) {
147  $path = self::normalizePathSeparator( realpath( $inputPath ) );
148  if ( !$path ) {
149  throw new \Exception( "Invalid path: $inputPath" );
150  }
151  if ( !str_starts_with( $path, $this->basepath ) ) {
152  throw new \Exception( "Path is not within basepath: $inputPath" );
153  }
154  $shortpath = substr( $path, strlen( $this->basepath ) );
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 similar 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 ( !str_starts_with( $inputPath, $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  if ( $result ) {
192  $shortpath = substr( $inputPath, $len );
193  $this->classes[$shortpath] = $result;
194  }
195  }
196 
200  public function readDir( $dir ) {
201  $it = new RecursiveDirectoryIterator(
202  self::normalizePathSeparator( realpath( $dir ) ) );
203  $it = new RecursiveIteratorIterator( $it );
204 
205  foreach ( $it as $path => $file ) {
206  if ( pathinfo( $path, PATHINFO_EXTENSION ) === 'php' ) {
207  $this->readFile( $path );
208  }
209  }
210  }
211 
220  protected function generateJsonAutoload( $filename ) {
221  $key = 'AutoloadClasses';
222  $json = FormatJson::decode( file_get_contents( $filename ), true );
223  unset( $json[$key] );
224  // Inverting the key-value pairs so that they become of the
225  // format class-name : path when they get converted into json.
226  foreach ( $this->classes as $path => $contained ) {
227  foreach ( $contained as $fqcn ) {
228  // Using substr to remove the leading '/'
229  $json[$key][$fqcn] = substr( $path, 1 );
230  }
231  }
232  foreach ( $this->overrides as $path => $fqcn ) {
233  // Using substr to remove the leading '/'
234  $json[$key][$fqcn] = substr( $path, 1 );
235  }
236 
237  // Sorting the list of autoload classes.
238  ksort( $json[$key] );
239 
240  // Return the whole JSON file
241  return FormatJson::encode( $json, "\t", FormatJson::ALL_OK ) . "\n";
242  }
243 
251  protected function generatePHPAutoload( $commandName, $filename ) {
252  // No existing JSON file found; update/generate PHP file
253  $content = [];
254 
255  // We need to generate a line each rather than exporting the
256  // full array so __DIR__ can be prepended to all the paths
257  $format = "%s => __DIR__ . %s,";
258  foreach ( $this->classes as $path => $contained ) {
259  $exportedPath = var_export( $path, true );
260  foreach ( $contained as $fqcn ) {
261  $content[$fqcn] = sprintf(
262  $format,
263  var_export( $fqcn, true ),
264  $exportedPath
265  );
266  }
267  }
268 
269  foreach ( $this->overrides as $fqcn => $path ) {
270  $content[$fqcn] = sprintf(
271  $format,
272  var_export( $fqcn, true ),
273  var_export( $path, true )
274  );
275  }
276 
277  // sort for stable output
278  ksort( $content );
279 
280  // extensions using this generator are appending to the existing
281  // autoload.
282  if ( $this->variableName === 'wgAutoloadClasses' ) {
283  $op = '+=';
284  } else {
285  $op = '=';
286  }
287 
288  $output = implode( "\n\t", $content );
289  return <<<EOD
290 <?php
291 // This file is generated by $commandName, do not adjust manually
292 // phpcs:disable Generic.Files.LineLength
293 global \${$this->variableName};
294 
295 \${$this->variableName} {$op} [
296  {$output}
297 ];
298 
299 EOD;
300  }
301 
310  public function getAutoload( $commandName = 'AutoloadGenerator' ) {
311  // We need to check whether an extension.json or skin.json exists or not, and
312  // incase it doesn't, update the autoload.php file.
313 
314  $fileinfo = $this->getTargetFileinfo();
315 
316  if ( $fileinfo['type'] === self::FILETYPE_JSON ) {
317  return $this->generateJsonAutoload( $fileinfo['filename'] );
318  }
319 
320  return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
321  }
322 
331  public function getTargetFileinfo() {
332  if ( file_exists( $this->basepath . '/extension.json' ) ) {
333  return [
334  'filename' => $this->basepath . '/extension.json',
335  'type' => self::FILETYPE_JSON
336  ];
337  }
338  if ( file_exists( $this->basepath . '/skin.json' ) ) {
339  return [
340  'filename' => $this->basepath . '/skin.json',
341  'type' => self::FILETYPE_JSON
342  ];
343  }
344 
345  return [
346  'filename' => $this->basepath . '/autoload.php',
347  'type' => self::FILETYPE_PHP
348  ];
349  }
350 
357  protected static function normalizePathSeparator( $path ) {
358  return str_replace( '\\', '/', $path );
359  }
360 
370  public function initMediaWikiDefault() {
371  foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
372  $this->readDir( $this->basepath . '/' . $dir );
373  }
374  foreach ( glob( $this->basepath . '/*.php' ) as $file ) {
375  $this->readFile( $file );
376  }
377  }
378 }
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.
static encode( $value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:98
static decode( $value, $assoc=false)
Decodes a JSON string.
Definition: FormatJson.php:148
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:57
$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