Update git submodules
[mediawiki.git] / includes / AutoLoader.php
blob421e2a4f5865e939f79a702de3107444ff47b59d
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\\Config\\' => __DIR__ . '/config/',
50 'MediaWiki\\Content\\' => __DIR__ . '/content/',
51 'MediaWiki\\DB\\' => __DIR__ . '/db/',
52 'MediaWiki\\Deferred\\' => __DIR__ . '/deferred/',
53 'MediaWiki\\Deferred\\LinksUpdate\\' => __DIR__ . '/deferred/LinksUpdate/',
54 'MediaWiki\\Diff\\' => __DIR__ . '/diff/',
55 'MediaWiki\\EditPage\\' => __DIR__ . '/editpage/',
56 'MediaWiki\\Edit\\' => __DIR__ . '/edit/',
57 'MediaWiki\\FileBackend\\LockManager\\' => __DIR__ . '/filebackend/lockmanager/',
58 'MediaWiki\\Http\\' => __DIR__ . '/http/',
59 'MediaWiki\\Installer\\' => __DIR__ . '/installer/',
60 'MediaWiki\\Interwiki\\' => __DIR__ . '/interwiki/',
61 'MediaWiki\\JobQueue\\' => __DIR__ . '/jobqueue/',
62 'MediaWiki\\Json\\' => __DIR__ . '/json/',
63 'MediaWiki\\Languages\\Data\\' => __DIR__ . '/languages/data/',
64 'MediaWiki\\Linker\\' => __DIR__ . '/linker/',
65 'MediaWiki\\Logger\\' => __DIR__ . '/debug/logger/',
66 'MediaWiki\\Logger\\Monolog\\' => __DIR__ . '/debug/logger/monolog/',
67 'MediaWiki\\Mail\\' => __DIR__ . '/mail/',
68 'MediaWiki\\Page\\' => __DIR__ . '/page/',
69 'MediaWiki\\Parser\\' => __DIR__ . '/parser/',
70 'MediaWiki\\PoolCounter\\' => __DIR__ . '/poolcounter/',
71 'MediaWiki\\Preferences\\' => __DIR__ . '/preferences/',
72 'MediaWiki\\Search\\' => __DIR__ . '/search/',
73 'MediaWiki\\Search\\SearchWidgets\\' => __DIR__ . '/search/searchwidgets/',
74 'MediaWiki\\Session\\' => __DIR__ . '/session/',
75 'MediaWiki\\Shell\\' => __DIR__ . '/shell/',
76 'MediaWiki\\Site\\' => __DIR__ . '/site/',
77 'MediaWiki\\Sparql\\' => __DIR__ . '/sparql/',
78 'MediaWiki\\SpecialPage\\' => __DIR__ . '/specialpage/',
79 'MediaWiki\\Specials\\Contribute\\' => __DIR__ . '/specials/Contribute',
80 'MediaWiki\\Tidy\\' => __DIR__ . '/tidy/',
81 'MediaWiki\\User\\' => __DIR__ . '/user/',
82 'MediaWiki\\Utils\\' => __DIR__ . '/utils/',
83 'MediaWiki\\Widget\\' => __DIR__ . '/widget/',
84 'Wikimedia\\' => __DIR__ . '/libs/',
85 'Wikimedia\\Http\\' => __DIR__ . '/libs/http/',
86 'Wikimedia\\Rdbms\\Platform\\' => __DIR__ . '/libs/rdbms/platform/',
87 'Wikimedia\\UUID\\' => __DIR__ . '/libs/uuid/',
90 /**
91 * @var string[] Namespace (ends with \) => Path (ends with /)
93 private static $psr4Namespaces = self::CORE_NAMESPACES;
95 /**
96 * @var string[] Class => File
98 private static $classFiles = [];
101 * Register a directory to load the classes of a given namespace from,
102 * per PSR4.
104 * @see <https://www.php-fig.org/psr/psr-4/>
105 * @since 1.39
106 * @param string[] $dirs a map of namespace (ends with \) to path (ends with /)
108 public static function registerNamespaces( array $dirs ): void {
109 self::$psr4Namespaces += $dirs;
113 * Register a file to load the given class from.
114 * @since 1.39
116 * @param string[] $files a map of qualified class names to file names
118 public static function registerClasses( array $files ): void {
119 self::$classFiles += $files;
123 * Load a file that declares classes, functions, or constants.
124 * The file will be loaded immediately using require_once in function scope.
126 * @note The file to be loaded MUST NOT set global variables or otherwise
127 * affect the global state. It MAY however use conditionals to determine
128 * what to declare and how, e.g. to provide polyfills.
130 * @note The file to be loaded MUST NOT assume that MediaWiki has been
131 * initialized. In particular, it MUST NOT access configuration variables
132 * or MediaWikiServices.
134 * @since 1.39
136 * @param string $file the path of the file to load.
138 public static function loadFile( string $file ): void {
139 require_once $file;
143 * Batch version of loadFile()
145 * @see loadFile()
147 * @since 1.39
149 * @param string[] $files the paths of the files to load.
151 public static function loadFiles( array $files ): void {
152 foreach ( $files as $f ) {
153 self::loadFile( $f );
158 * Find the file containing the given class.
160 * @param string $className Name of class we're looking for.
161 * @return string|null The path containing the class, not null if not found
163 public static function find( $className ): ?string {
164 global $wgAutoloadLocalClasses, $wgAutoloadClasses;
166 // NOTE: $wgAutoloadClasses is supported for compatibility with old-style extension
167 // registration files.
169 $filename = $wgAutoloadLocalClasses[$className] ??
170 self::$classFiles[$className] ??
171 $wgAutoloadClasses[$className] ??
172 false;
174 if ( !$filename && strpos( $className, '\\' ) !== false ) {
175 // This class is namespaced, so look in the namespace map
176 $prefix = $className;
177 while ( ( $pos = strrpos( $prefix, '\\' ) ) !== false ) {
178 // Check to see if this namespace prefix is in the map
179 $prefix = substr( $className, 0, $pos + 1 );
180 if ( isset( self::$psr4Namespaces[$prefix] ) ) {
181 $relativeClass = substr( $className, $pos + 1 );
182 // Build the expected filename, and see if it exists
183 $file = self::$psr4Namespaces[$prefix] .
184 '/' .
185 strtr( $relativeClass, '\\', '/' ) .
186 '.php';
187 if ( is_file( $file ) ) {
188 $filename = $file;
189 break;
193 // Remove trailing separator for next iteration
194 $prefix = rtrim( $prefix, '\\' );
198 if ( !$filename ) {
199 // Class not found; let the next autoloader try to find it
200 return null;
203 // Make an absolute path, this improves performance by avoiding some stat calls
204 // Optimisation: use string offset access instead of substr
205 if ( $filename[0] !== '/' && $filename[1] !== ':' ) {
206 $filename = __DIR__ . '/../' . $filename;
209 return $filename;
213 * autoload - take a class name and attempt to load it
215 * @param string $className Name of class we're looking for.
217 public static function autoload( $className ) {
218 $filename = self::find( $className );
220 if ( $filename !== null ) {
221 require $filename;
225 ///// Methods used during testing //////////////////////////////////////////////
226 private static function assertTesting( $method ) {
227 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
228 throw new LogicException( "$method is not supported outside phpunit tests!" );
233 * Returns a map of class names to file paths for testing.
234 * @note Will throw if called outside of phpunit tests!
235 * @return string[]
237 public static function getClassFiles(): array {
238 global $wgAutoloadLocalClasses, $wgAutoloadClasses;
240 self::assertTesting( __METHOD__ );
242 // NOTE: ensure the order of preference is the same as used by find().
243 return array_merge(
244 $wgAutoloadClasses,
245 self::$classFiles,
246 $wgAutoloadLocalClasses
251 * Returns a map of namespace names to directories, per PSR4.
252 * @note Will throw if called outside of phpunit tests!
253 * @return string[]
255 public static function getNamespaceDirectories(): array {
256 self::assertTesting( __METHOD__ );
257 return self::$psr4Namespaces;
261 * Returns an array representing the internal state of Autoloader,
262 * so it can be remembered and later restored during testing.
263 * @internal
264 * @note Will throw if called outside of phpunit tests!
265 * @return array
267 public static function getState(): array {
268 self::assertTesting( __METHOD__ );
269 return [
270 'classFiles' => self::$classFiles,
271 'psr4Namespaces' => self::$psr4Namespaces,
276 * Returns an array representing the internal state of Autoloader,
277 * so it can be remembered and later restored during testing.
278 * @internal
279 * @note Will throw if called outside of phpunit tests!
281 * @param array $state A state array returned by getState().
283 public static function restoreState( $state ): void {
284 self::assertTesting( __METHOD__ );
286 self::$classFiles = $state['classFiles'];
287 self::$psr4Namespaces = $state['psr4Namespaces'];
292 spl_autoload_register( [ 'AutoLoader', 'autoload' ] );
294 // Load composer's autoloader if present
295 if ( is_readable( __DIR__ . '/../vendor/autoload.php' ) ) {
296 require_once __DIR__ . '/../vendor/autoload.php';
297 } elseif ( file_exists( __DIR__ . '/../vendor/autoload.php' ) ) {
298 die( __DIR__ . '/../vendor/autoload.php exists but is not readable' );