Merge "ResourceLoader: Deprecate ResourceLoader::makeConfigSetScript"
[mediawiki.git] / includes / AutoLoader.php
blob6b8d447a2863dfe9c69da9a304948db0fb0f601c
1 <?php
2 /**
3 * This defines autoloading handler for whole MediaWiki framework
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 // NO_AUTOLOAD -- file scope code, can't load self
25 /**
26 * Locations of core classes
27 * Extension classes are specified with $wgAutoloadClasses
29 require_once __DIR__ . '/../autoload.php';
31 class AutoLoader {
33 /**
34 * A mapping of namespace => file path for MediaWiki core.
35 * The namespaces should follow the PSR-4 standard for autoloading
37 * @see <https://www.php-fig.org/psr/psr-4/>
38 * @internal Only public for usage in AutoloadGenerator
39 * @phpcs-require-sorted-array
41 public const CORE_NAMESPACES = [
42 'MediaWiki\\' => __DIR__ . '/',
43 'MediaWiki\\Actions\\' => __DIR__ . '/actions/',
44 'MediaWiki\\Api\\' => __DIR__ . '/api/',
45 'MediaWiki\\Auth\\' => __DIR__ . '/auth/',
46 'MediaWiki\\Block\\' => __DIR__ . '/block/',
47 'MediaWiki\\Cache\\' => __DIR__ . '/cache/',
48 'MediaWiki\\ChangeTags\\' => __DIR__ . '/changetags/',
49 'MediaWiki\\Composer\\' => __DIR__ . '/composer/',
50 'MediaWiki\\Config\\' => __DIR__ . '/config/',
51 'MediaWiki\\Content\\' => __DIR__ . '/content/',
52 'MediaWiki\\DB\\' => __DIR__ . '/db/',
53 'MediaWiki\\Deferred\\' => __DIR__ . '/deferred/',
54 'MediaWiki\\Deferred\\LinksUpdate\\' => __DIR__ . '/deferred/LinksUpdate/',
55 'MediaWiki\\Diff\\' => __DIR__ . '/diff/',
56 'MediaWiki\\EditPage\\' => __DIR__ . '/editpage/',
57 'MediaWiki\\Edit\\' => __DIR__ . '/edit/',
58 'MediaWiki\\FileBackend\\LockManager\\' => __DIR__ . '/filebackend/lockmanager/',
59 'MediaWiki\\Http\\' => __DIR__ . '/http/',
60 'MediaWiki\\Installer\\' => __DIR__ . '/installer/',
61 'MediaWiki\\Interwiki\\' => __DIR__ . '/interwiki/',
62 'MediaWiki\\JobQueue\\' => __DIR__ . '/jobqueue/',
63 'MediaWiki\\Json\\' => __DIR__ . '/json/',
64 'MediaWiki\\Languages\\Data\\' => __DIR__ . '/languages/data/',
65 'MediaWiki\\Linker\\' => __DIR__ . '/linker/',
66 'MediaWiki\\Logger\\' => __DIR__ . '/debug/logger/',
67 'MediaWiki\\Logger\\Monolog\\' => __DIR__ . '/debug/logger/monolog/',
68 'MediaWiki\\Mail\\' => __DIR__ . '/mail/',
69 'MediaWiki\\Page\\' => __DIR__ . '/page/',
70 'MediaWiki\\Parser\\' => __DIR__ . '/parser/',
71 'MediaWiki\\Password\\' => __DIR__ . '/password/',
72 'MediaWiki\\PoolCounter\\' => __DIR__ . '/poolcounter/',
73 'MediaWiki\\Preferences\\' => __DIR__ . '/preferences/',
74 'MediaWiki\\RCFeed\\' => __DIR__ . '/recentchanges/RCFeed/',
75 'MediaWiki\\Search\\' => __DIR__ . '/search/',
76 'MediaWiki\\Search\\SearchWidgets\\' => __DIR__ . '/search/searchwidgets/',
77 'MediaWiki\\Session\\' => __DIR__ . '/session/',
78 'MediaWiki\\Shell\\' => __DIR__ . '/shell/',
79 'MediaWiki\\Site\\' => __DIR__ . '/site/',
80 'MediaWiki\\Sparql\\' => __DIR__ . '/sparql/',
81 'MediaWiki\\SpecialPage\\' => __DIR__ . '/specialpage/',
82 'MediaWiki\\Specials\\Contribute\\' => __DIR__ . '/specials/Contribute',
83 'MediaWiki\\Tidy\\' => __DIR__ . '/tidy/',
84 'MediaWiki\\User\\' => __DIR__ . '/user/',
85 'MediaWiki\\Utils\\' => __DIR__ . '/utils/',
86 'MediaWiki\\Widget\\' => __DIR__ . '/widget/',
87 'Wikimedia\\' => __DIR__ . '/libs/',
88 'Wikimedia\\Composer\\' => __DIR__ . '/libs/composer/',
89 'Wikimedia\\Http\\' => __DIR__ . '/libs/http/',
90 'Wikimedia\\Rdbms\\Platform\\' => __DIR__ . '/libs/rdbms/platform/',
91 'Wikimedia\\UUID\\' => __DIR__ . '/libs/uuid/',
94 /**
95 * @var string[] Namespace (ends with \) => Path (ends with /)
97 private static $psr4Namespaces = self::CORE_NAMESPACES;
99 /**
100 * @var string[] Class => File
102 private static $classFiles = [];
105 * Register a directory to load the classes of a given namespace from,
106 * per PSR4.
108 * @see <https://www.php-fig.org/psr/psr-4/>
109 * @since 1.39
110 * @param string[] $dirs a map of namespace (ends with \) to path (ends with /)
112 public static function registerNamespaces( array $dirs ): void {
113 self::$psr4Namespaces += $dirs;
117 * Register a file to load the given class from.
118 * @since 1.39
120 * @param string[] $files a map of qualified class names to file names
122 public static function registerClasses( array $files ): void {
123 self::$classFiles += $files;
127 * Load a file that declares classes, functions, or constants.
128 * The file will be loaded immediately using require_once in function scope.
130 * @note The file to be loaded MUST NOT set global variables or otherwise
131 * affect the global state. It MAY however use conditionals to determine
132 * what to declare and how, e.g. to provide polyfills.
134 * @note The file to be loaded MUST NOT assume that MediaWiki has been
135 * initialized. In particular, it MUST NOT access configuration variables
136 * or MediaWikiServices.
138 * @since 1.39
140 * @param string $file the path of the file to load.
142 public static function loadFile( string $file ): void {
143 require_once $file;
147 * Batch version of loadFile()
149 * @see loadFile()
151 * @since 1.39
153 * @param string[] $files the paths of the files to load.
155 public static function loadFiles( array $files ): void {
156 foreach ( $files as $f ) {
157 self::loadFile( $f );
162 * Find the file containing the given class.
164 * @param string $className Name of class we're looking for.
165 * @return string|null The path containing the class, not null if not found
167 public static function find( $className ): ?string {
168 global $wgAutoloadLocalClasses, $wgAutoloadClasses;
170 // NOTE: $wgAutoloadClasses is supported for compatibility with old-style extension
171 // registration files.
173 $filename = $wgAutoloadLocalClasses[$className] ??
174 self::$classFiles[$className] ??
175 $wgAutoloadClasses[$className] ??
176 false;
178 if ( !$filename && strpos( $className, '\\' ) !== false ) {
179 // This class is namespaced, so look in the namespace map
180 $prefix = $className;
181 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
182 while ( ( $pos = strrpos( $prefix, '\\' ) ) !== false ) {
183 // Check to see if this namespace prefix is in the map
184 $prefix = substr( $className, 0, $pos + 1 );
185 if ( isset( self::$psr4Namespaces[$prefix] ) ) {
186 $relativeClass = substr( $className, $pos + 1 );
187 // Build the expected filename, and see if it exists
188 $file = self::$psr4Namespaces[$prefix] .
189 '/' .
190 strtr( $relativeClass, '\\', '/' ) .
191 '.php';
192 if ( is_file( $file ) ) {
193 $filename = $file;
194 break;
198 // Remove trailing separator for next iteration
199 $prefix = rtrim( $prefix, '\\' );
203 if ( !$filename ) {
204 // Class not found; let the next autoloader try to find it
205 return null;
208 // Make an absolute path, this improves performance by avoiding some stat calls
209 // Optimisation: use string offset access instead of substr
210 if ( $filename[0] !== '/' && $filename[1] !== ':' ) {
211 $filename = __DIR__ . '/../' . $filename;
214 return $filename;
218 * autoload - take a class name and attempt to load it
220 * @param string $className Name of class we're looking for.
222 public static function autoload( $className ) {
223 $filename = self::find( $className );
225 if ( $filename !== null ) {
226 require_once $filename;
230 ///// Methods used during testing //////////////////////////////////////////////
231 private static function assertTesting( $method ) {
232 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
233 throw new LogicException( "$method is not supported outside phpunit tests!" );
238 * Returns a map of class names to file paths for testing.
239 * @note Will throw if called outside of phpunit tests!
240 * @return string[]
242 public static function getClassFiles(): array {
243 global $wgAutoloadLocalClasses, $wgAutoloadClasses;
245 self::assertTesting( __METHOD__ );
247 // NOTE: ensure the order of preference is the same as used by find().
248 return array_merge(
249 $wgAutoloadClasses,
250 self::$classFiles,
251 $wgAutoloadLocalClasses
256 * Returns a map of namespace names to directories, per PSR4.
257 * @note Will throw if called outside of phpunit tests!
258 * @return string[]
260 public static function getNamespaceDirectories(): array {
261 self::assertTesting( __METHOD__ );
262 return self::$psr4Namespaces;
266 * Returns an array representing the internal state of Autoloader,
267 * so it can be remembered and later restored during testing.
268 * @internal
269 * @note Will throw if called outside of phpunit tests!
270 * @return array
272 public static function getState(): array {
273 self::assertTesting( __METHOD__ );
274 return [
275 'classFiles' => self::$classFiles,
276 'psr4Namespaces' => self::$psr4Namespaces,
281 * Returns an array representing the internal state of Autoloader,
282 * so it can be remembered and later restored during testing.
283 * @internal
284 * @note Will throw if called outside of phpunit tests!
286 * @param array $state A state array returned by getState().
288 public static function restoreState( $state ): void {
289 self::assertTesting( __METHOD__ );
291 self::$classFiles = $state['classFiles'];
292 self::$psr4Namespaces = $state['psr4Namespaces'];
297 spl_autoload_register( [ 'AutoLoader', 'autoload' ] );
299 // Load composer's autoloader if present
300 if ( is_readable( __DIR__ . '/../vendor/autoload.php' ) ) {
301 require_once __DIR__ . '/../vendor/autoload.php';
302 } elseif ( file_exists( __DIR__ . '/../vendor/autoload.php' ) ) {
303 die( __DIR__ . '/../vendor/autoload.php exists but is not readable' );