3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
22 * Accepts a list of files and directories to search for
23 * php files and generates $wgAutoloadLocalClasses or $wgAutoloadClasses
24 * lines for all detected classes. These lines are written out
25 * to an autoload.php file in the projects provided basedir.
29 * $gen = new AutoloadGenerator( __DIR__ );
30 * $gen->readDir( __DIR__ . '/includes' );
31 * $gen->readFile( __DIR__ . '/foo.php' )
32 * $gen->getAutoload();
34 class AutoloadGenerator
{
35 const FILETYPE_JSON
= 'json';
36 const FILETYPE_PHP
= 'php';
39 * @var string Root path of the project being scanned for classes
44 * @var ClassCollector Helper class extracts class names from php files
49 * @var array Map of file shortpath to list of FQCN detected within file
51 protected $classes = [];
54 * @var string The global variable to write output to
56 protected $variableName = 'wgAutoloadClasses';
59 * @var array Map of FQCN to relative path(from self::$basepath)
61 protected $overrides = [];
64 * Directories that should be excluded
68 protected $excludePaths = [];
71 * Configured PSR4 namespaces
73 * @var string[] namespace => path
75 protected $psr4Namespaces = [];
78 * @param string $basepath Root path of the project being scanned for classes
79 * @param array|string $flags
81 * local - If this flag is set $wgAutoloadLocalClasses will be build instead
82 * of $wgAutoloadClasses
84 public function __construct( $basepath, $flags = [] ) {
85 if ( !is_array( $flags ) ) {
88 $this->basepath
= self
::normalizePathSeparator( realpath( $basepath ) );
89 $this->collector
= new ClassCollector
;
90 if ( in_array( 'local', $flags ) ) {
91 $this->variableName
= 'wgAutoloadLocalClasses';
96 * Directories that should be excluded
99 * @param string[] $paths
101 public function setExcludePaths( array $paths ) {
102 foreach ( $paths as $path ) {
103 $this->excludePaths
[] = self
::normalizePathSeparator( $path );
108 * Set PSR4 namespaces
110 * Unlike self::setExcludePaths(), this will only skip outputting the
111 * autoloader entry when the namespace matches the path.
114 * @param string[] $namespaces Associative array mapping namespace to path
116 public function setPsr4Namespaces( array $namespaces ) {
117 foreach ( $namespaces as $ns => $path ) {
118 $ns = rtrim( $ns, '\\' ) . '\\';
119 $this->psr4Namespaces
[$ns] = rtrim( self
::normalizePathSeparator( $path ), '/' );
124 * Whether the file should be excluded
126 * @param string $path File path
129 private function shouldExclude( $path ) {
130 foreach ( $this->excludePaths
as $dir ) {
131 if ( strpos( $path, $dir ) === 0 ) {
140 * Force a class to be autoloaded from a specific path, regardless of where
141 * or if it was detected.
143 * @param string $fqcn FQCN to force the location of
144 * @param string $inputPath Full path to the file containing the class
147 public function forceClassPath( $fqcn, $inputPath ) {
148 $path = self
::normalizePathSeparator( realpath( $inputPath ) );
150 throw new \
Exception( "Invalid path: $inputPath" );
152 $len = strlen( $this->basepath
);
153 if ( substr( $path, 0, $len ) !== $this->basepath
) {
154 throw new \
Exception( "Path is not within basepath: $inputPath" );
156 $shortpath = substr( $path, $len );
157 $this->overrides
[$fqcn] = $shortpath;
161 * @param string $inputPath Path to a php file to find classes within
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" );
173 if ( $this->shouldExclude( $inputPath ) ) {
176 $result = $this->collector
->getClasses(
177 file_get_contents( $inputPath )
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 ) )
189 if ( $inputPath === $expectedPath ) {
199 $shortpath = substr( $inputPath, $len );
200 $this->classes
[$shortpath] = $result;
205 * @param string $dir Path to a directory to recursively search
206 * for php files with either .php or .inc extensions
208 public function readDir( $dir ) {
209 $it = new RecursiveDirectoryIterator(
210 self
::normalizePathSeparator( realpath( $dir ) ) );
211 $it = new RecursiveIteratorIterator( $it );
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 );
223 * Updates the AutoloadClasses field at the given
226 * @param string $filename Filename of JSON
227 * extension/skin registration file
228 * @return string Updated Json of the file given as the $filename parameter
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 );
242 foreach ( $this->overrides
as $path => $fqcn ) {
243 // Using substr to remove the leading '/'
244 $json[$key][$fqcn] = substr( $path, 1 );
247 // Sorting the list of autoload classes.
248 ksort( $json[$key] );
250 // Return the whole JSON file
251 return FormatJson
::encode( $json, "\t", FormatJson
::ALL_OK
) . "\n";
255 * Generates a PHP file setting up autoload information.
257 * @param string $commandName Command name to include in comment
258 * @param string $filename of PHP file to put autoload information in.
261 protected function generatePHPAutoload( $commandName, $filename ) {
262 // No existing JSON file found; update/generate PHP file
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(
273 var_export( $fqcn, true ),
279 foreach ( $this->overrides
as $fqcn => $path ) {
280 $content[$fqcn] = sprintf(
282 var_export( $fqcn, true ),
283 var_export( $path, true )
287 // sort for stable output
290 // extensions using this generator are appending to the existing
292 if ( $this->variableName
=== 'wgAutoloadClasses' ) {
298 $output = implode( "\n\t", $content );
301 // This file is generated by $commandName, do not adjust manually
302 // phpcs:disable Generic.Files.LineLength
303 global \${$this->variableName};
305 \${$this->variableName} {$op} [
313 * Returns all known classes as a string, which can be used to put into a target
314 * file (e.g. extension.json, skin.json or autoload.php)
316 * @param string $commandName Value used in file comment to direct
317 * developers towards the appropriate way to update the autoload.
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.
324 $fileinfo = $this->getTargetFileinfo();
326 if ( $fileinfo['type'] === self
::FILETYPE_JSON
) {
327 return $this->generateJsonAutoload( $fileinfo['filename'] );
329 return $this->generatePHPAutoload( $commandName, $fileinfo['filename'] );
334 * Returns the filename of the extension.json of skin.json, if there's any, or
335 * otherwise the path to the autoload.php file in an array as the "filename"
336 * key and with the type (AutoloadGenerator::FILETYPE_JSON or AutoloadGenerator::FILETYPE_PHP)
337 * of the file as the "type" key.
341 public function getTargetFileinfo() {
343 'filename' => $this->basepath
. '/autoload.php',
344 'type' => self
::FILETYPE_PHP
346 if ( file_exists( $this->basepath
. '/extension.json' ) ) {
348 'filename' => $this->basepath
. '/extension.json',
349 'type' => self
::FILETYPE_JSON
351 } elseif ( file_exists( $this->basepath
. '/skin.json' ) ) {
353 'filename' => $this->basepath
. '/skin.json',
354 'type' => self
::FILETYPE_JSON
362 * Ensure that Unix-style path separators ("/") are used in the path.
364 * @param string $path
367 protected static function normalizePathSeparator( $path ) {
368 return str_replace( '\\', '/', $path );
372 * Initialize the source files and directories which are used for the MediaWiki default
373 * autoloader in {mw-base-dir}/autoload.php including:
380 public function initMediaWikiDefault() {
381 foreach ( [ 'includes', 'languages', 'maintenance', 'mw-config' ] as $dir ) {
382 $this->readDir( $this->basepath
. '/' . $dir );
384 foreach ( glob( $this->basepath
. '/*.php' ) as $file ) {
385 $this->readFile( $file );