Debian Codegraph @

includes/AutoLoader.php

raw symbols SCIP
1 <?php
2 /**
3 * This defines autoloading handler for whole MediaWiki framework
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
23 // NO_AUTOLOAD -- file scope code, can't load self
24
25 /**
26 * Locations of core classes
27 * Extension classes are specified with $wgAutoloadClasses
28 */
29 require_once __DIR__ . '/../autoload.php';
30
31 class AutoLoader {
32
33 /**
34 * A mapping of namespace => file path for MediaWiki core.
35 * The namespaces should follow the PSR-4 standard for autoloading
36 *
37 * @see <https://www.php-fig.org/psr/psr-4/>
38 * @internal Only public for usage in AutoloadGenerator
39 * @phpcs-require-sorted-array
40 */
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\\Collation\\' => __DIR__ . '/collation/',
50 'MediaWiki\\Composer\\' => __DIR__ . '/composer/',
51 'MediaWiki\\Config\\' => __DIR__ . '/config/',
52 'MediaWiki\\Content\\' => __DIR__ . '/content/',
53 'MediaWiki\\Context\\' => __DIR__ . '/context/',
54 'MediaWiki\\DAO\\' => __DIR__ . '/dao/',
55 'MediaWiki\\DB\\' => __DIR__ . '/db/',
56 'MediaWiki\\Debug\\' => __DIR__ . '/debug/',
57 'MediaWiki\\Deferred\\' => __DIR__ . '/deferred/',
58 'MediaWiki\\Deferred\\LinksUpdate\\' => __DIR__ . '/deferred/LinksUpdate/',
59 'MediaWiki\\Diff\\' => __DIR__ . '/diff/',
60 'MediaWiki\\EditPage\\' => __DIR__ . '/editpage/',
61 'MediaWiki\\Edit\\' => __DIR__ . '/edit/',
62 'MediaWiki\\Exception\\' => __DIR__ . '/exception/',
63 'MediaWiki\\Export\\' => __DIR__ . '/export/',
64 'MediaWiki\\FileBackend\\' => __DIR__ . '/filebackend/',
65 'MediaWiki\\FileBackend\\FSFile\\' => __DIR__ . '/libs/filebackend/fsfile/',
66 'MediaWiki\\FileBackend\\LockManager\\' => __DIR__ . '/filebackend/lockmanager/',
67 'MediaWiki\\FileRepo\\' => __DIR__ . '/filerepo/',
68 'MediaWiki\\FileRepo\\File\\' => __DIR__ . '/filerepo/file/',
69 'MediaWiki\\HTMLForm\\' => __DIR__ . '/htmlform/',
70 'MediaWiki\\HTMLForm\\Field\\' => __DIR__ . '/htmlform/fields/',
71 'MediaWiki\\Http\\' => __DIR__ . '/http/',
72 'MediaWiki\\Installer\\' => __DIR__ . '/installer/',
73 'MediaWiki\\Interwiki\\' => __DIR__ . '/interwiki/',
74 'MediaWiki\\JobQueue\\' => __DIR__ . '/jobqueue/',
75 'MediaWiki\\JobQueue\\Exceptions\\' => __DIR__ . '/jobqueue/exception/',
76 'MediaWiki\\JobQueue\\Jobs\\' => __DIR__ . '/jobqueue/jobs/',
77 'MediaWiki\\JobQueue\\Utils\\' => __DIR__ . '/jobqueue/utils/',
78 'MediaWiki\\Json\\' => __DIR__ . '/json/',
79 'MediaWiki\\Languages\\' => __DIR__ . '/language/',
80 'MediaWiki\\Languages\\Data\\' => __DIR__ . '/languages/data/',
81 'MediaWiki\\Language\\' => __DIR__ . '/language/',
82 'MediaWiki\\Libs\\' => __DIR__ . '/libs/',
83 'MediaWiki\\LinkedData\\' => __DIR__ . '/linkeddata/',
84 'MediaWiki\\Linker\\' => __DIR__ . '/linker/',
85 'MediaWiki\\Logger\\' => __DIR__ . '/debug/logger/',
86 'MediaWiki\\Logger\\Monolog\\' => __DIR__ . '/debug/logger/monolog/',
87 'MediaWiki\\Logging\\' => __DIR__ . '/logging/',
88 'MediaWiki\\Mail\\' => __DIR__ . '/mail/',
89 'MediaWiki\\Maintenance\\' => __DIR__ . '/../maintenance/includes/',
90 'MediaWiki\\Page\\' => __DIR__ . '/page/',
91 'MediaWiki\\Parser\\' => __DIR__ . '/parser/',
92 'MediaWiki\\Password\\' => __DIR__ . '/password/',
93 'MediaWiki\\PoolCounter\\' => __DIR__ . '/poolcounter/',
94 'MediaWiki\\Preferences\\' => __DIR__ . '/preferences/',
95 'MediaWiki\\Profiler\\' => __DIR__ . '/profiler/',
96 'MediaWiki\\RCFeed\\' => __DIR__ . '/recentchanges/RCFeed/',
97 'MediaWiki\\RecentChanges\\' => __DIR__ . '/recentchanges/',
98 'MediaWiki\\Registration\\' => __DIR__ . '/registration/',
99 'MediaWiki\\RevisionList\\' => __DIR__ . '/revisionlist/',
100 'MediaWiki\\Search\\' => __DIR__ . '/search/',
101 'MediaWiki\\Search\\SearchWidgets\\' => __DIR__ . '/search/searchwidgets/',
102 'MediaWiki\\Session\\' => __DIR__ . '/session/',
103 'MediaWiki\\Shell\\' => __DIR__ . '/shell/',
104 'MediaWiki\\Site\\' => __DIR__ . '/site/',
105 'MediaWiki\\Skin\\' => __DIR__ . '/skins/',
106 'MediaWiki\\Sparql\\' => __DIR__ . '/sparql/',
107 'MediaWiki\\SpecialPage\\' => __DIR__ . '/specialpage/',
108 'MediaWiki\\Specials\\' => __DIR__ . '/specials/',
109 'MediaWiki\\Specials\\Contribute\\' => __DIR__ . '/specials/Contribute/',
110 'MediaWiki\\Specials\\Redirects\\' => __DIR__ . '/specials/redirects/',
111 'MediaWiki\\Tidy\\' => __DIR__ . '/tidy/',
112 'MediaWiki\\Title\\' => __DIR__ . '/title/',
113 'MediaWiki\\User\\' => __DIR__ . '/user/',
114 'MediaWiki\\Utils\\' => __DIR__ . '/utils/',
115 'MediaWiki\\Watchlist\\' => __DIR__ . '/watchlist/',
116 'MediaWiki\\Widget\\' => __DIR__ . '/widget/',
117 'MediaWiki\\Xml\\' => __DIR__ . '/xml/',
118 'Wikimedia\\' => __DIR__ . '/libs/',
119 'Wikimedia\\ArrayUtils\\' => __DIR__ . '/libs/',
120 'Wikimedia\\Composer\\' => __DIR__ . '/libs/composer/',
121 'Wikimedia\\DependencyStore\\' => __DIR__ . '/ResourceLoader/dependencystore/',
122 'Wikimedia\\EventRelayer\\' => __DIR__ . '/libs/eventrelayer/',
123 'Wikimedia\\FileBackend\\' => __DIR__ . '/libs/filebackend/',
124 'Wikimedia\\FileBackend\\FileIteration\\' => __DIR__ . '/libs/filebackend/fileiteration/',
125 'Wikimedia\\FileBackend\\FileOpHandle\\' => __DIR__ . '/libs/filebackend/fileophandle/',
126 'Wikimedia\\FileBackend\\FileOps\\' => __DIR__ . '/libs/filebackend/fileop/',
127 'Wikimedia\\FileBackend\\FSFile\\' => __DIR__ . '/libs/filebackend/fsfile/',
128 'Wikimedia\\HashRing\\' => __DIR__ . '/libs/',
129 'Wikimedia\\HtmlArmor\\' => __DIR__ . '/libs/',
130 'Wikimedia\\Http\\' => __DIR__ . '/libs/http/',
131 'Wikimedia\\LightweightObjectStore\\' => __DIR__ . '/libs/objectcache/utils/',
132 'Wikimedia\\MapCacheLRU\\' => __DIR__ . '/libs/',
133 'Wikimedia\\Mime\\' => __DIR__ . '/libs/mime/',
134 'Wikimedia\\NonSerializable\\' => __DIR__ . '/libs/',
135 'Wikimedia\\ObjectCache\\' => __DIR__ . '/libs/objectcache/',
136 'Wikimedia\\Rdbms\\Database\\' => __DIR__ . '/libs/rdbms/database/',
137 'Wikimedia\\Rdbms\\Platform\\' => __DIR__ . '/libs/rdbms/platform/',
138 'Wikimedia\\Rdbms\\Replication\\' => __DIR__ . '/libs/rdbms/database/replication/',
139 'Wikimedia\\StringUtils\\' => __DIR__ . '/libs/',
140 'Wikimedia\\Telemetry\\' => __DIR__ . '/libs/telemetry/',
141 'Wikimedia\\Timing\\' => __DIR__ . '/libs/',
142 'Wikimedia\\UUID\\' => __DIR__ . '/libs/uuid/',
143 ];
144
145 /**
146 * @var string[] Namespace (ends with \) => Path (ends with /)
147 */
148 private static $psr4Namespaces = self::CORE_NAMESPACES;
149
150 /**
151 * @var string[] Class => File
152 */
153 private static $classFiles = [];
154
155 /**
156 * Register a directory to load the classes of a given namespace from,
157 * per PSR4.
158 *
159 * @see <https://www.php-fig.org/psr/psr-4/>
160 * @since 1.39
161 * @param string[] $dirs a map of namespace (ends with \) to path (ends with /)
162 */
163 public static function registerNamespaces( array $dirs ): void {
164 self::$psr4Namespaces += $dirs;
165 }
166
167 /**
168 * Register a file to load the given class from.
169 * @since 1.39
170 *
171 * @param string[] $files a map of qualified class names to file names
172 */
173 public static function registerClasses( array $files ): void {
174 self::$classFiles += $files;
175 }
176
177 /**
178 * Load a file that declares classes, functions, or constants.
179 * The file will be loaded immediately using require_once in function scope.
180 *
181 * @note The file to be loaded MUST NOT set global variables or otherwise
182 * affect the global state. It MAY however use conditionals to determine
183 * what to declare and how, e.g. to provide polyfills.
184 *
185 * @note The file to be loaded MUST NOT assume that MediaWiki has been
186 * initialized. In particular, it MUST NOT access configuration variables
187 * or MediaWikiServices.
188 *
189 * @since 1.39
190 *
191 * @param string $file the path of the file to load.
192 */
193 public static function loadFile( string $file ): void {
194 require_once $file;
195 }
196
197 /**
198 * Batch version of loadFile()
199 *
200 * @see loadFile()
201 *
202 * @since 1.39
203 *
204 * @param string[] $files the paths of the files to load.
205 */
206 public static function loadFiles( array $files ): void {
207 foreach ( $files as $f ) {
208 self::loadFile( $f );
209 }
210 }
211
212 /**
213 * Find the file containing the given class.
214 *
215 * @param string $className Name of class we're looking for.
216 * @return string|null The path containing the class, not null if not found
217 */
218 public static function find( $className ): ?string {
219 global $wgAutoloadLocalClasses, $wgAutoloadClasses;
220
221 // NOTE: $wgAutoloadClasses is supported for compatibility with old-style extension
222 // registration files.
223
224 $filename = $wgAutoloadLocalClasses[$className] ??
225 self::$classFiles[$className] ??
226 $wgAutoloadClasses[$className] ??
227 false;
228
229 if ( !$filename && strpos( $className, '\\' ) !== false ) {
230 // This class is namespaced, so look in the namespace map
231 $prefix = $className;
232 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
233 while ( ( $pos = strrpos( $prefix, '\\' ) ) !== false ) {
234 // Check to see if this namespace prefix is in the map
235 $prefix = substr( $className, 0, $pos + 1 );
236 if ( isset( self::$psr4Namespaces[$prefix] ) ) {
237 $relativeClass = substr( $className, $pos + 1 );
238 // Build the expected filename, and see if it exists
239 $file = self::$psr4Namespaces[$prefix] .
240 '/' .
241 strtr( $relativeClass, '\\', '/' ) .
242 '.php';
243 if ( is_file( $file ) ) {
244 $filename = $file;
245 break;
246 }
247 }
248
249 // Remove trailing separator for next iteration
250 $prefix = rtrim( $prefix, '\\' );
251 }
252 }
253
254 if ( !$filename ) {
255 // Class not found; let the next autoloader try to find it
256 return null;
257 }
258
259 // Make an absolute path, this improves performance by avoiding some stat calls
260 // Optimisation: use string offset access instead of substr
261 if ( $filename[0] !== '/' && $filename[1] !== ':' ) {
262 $filename = __DIR__ . '/../' . $filename;
263 }
264
265 return $filename;
266 }
267
268 /**
269 * autoload - take a class name and attempt to load it
270 *
271 * @param string $className Name of class we're looking for.
272 */
273 public static function autoload( $className ) {
274 $filename = self::find( $className );
275
276 if ( $filename !== null ) {
277 require_once $filename;
278 }
279 }
280
281 ///// Methods used during testing //////////////////////////////////////////////
282 private static function assertTesting( $method ) {
283 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
284 throw new LogicException( "$method is not supported outside phpunit tests!" );
285 }
286 }
287
288 /**
289 * Returns a map of class names to file paths for testing.
290 * @note Will throw if called outside of phpunit tests!
291 * @return string[]
292 */
293 public static function getClassFiles(): array {
294 global $wgAutoloadLocalClasses, $wgAutoloadClasses;
295
296 self::assertTesting( __METHOD__ );
297
298 // NOTE: ensure the order of preference is the same as used by find().
299 return array_merge(
300 $wgAutoloadClasses,
301 self::$classFiles,
302 $wgAutoloadLocalClasses
303 );
304 }
305
306 /**
307 * Returns a map of namespace names to directories, per PSR4.
308 * @note Will throw if called outside of phpunit tests!
309 * @return string[]
310 */
311 public static function getNamespaceDirectories(): array {
312 self::assertTesting( __METHOD__ );
313 return self::$psr4Namespaces;
314 }
315
316 /**
317 * Returns an array representing the internal state of Autoloader,
318 * so it can be remembered and later restored during testing.
319 * @internal
320 * @note Will throw if called outside of phpunit tests!
321 * @return array
322 */
323 public static function getState(): array {
324 self::assertTesting( __METHOD__ );
325 return [
326 'classFiles' => self::$classFiles,
327 'psr4Namespaces' => self::$psr4Namespaces,
328 ];
329 }
330
331 /**
332 * Returns an array representing the internal state of Autoloader,
333 * so it can be remembered and later restored during testing.
334 * @internal
335 * @note Will throw if called outside of phpunit tests!
336 *
337 * @param array $state A state array returned by getState().
338 */
339 public static function restoreState( $state ): void {
340 self::assertTesting( __METHOD__ );
341
342 self::$classFiles = $state['classFiles'];
343 self::$psr4Namespaces = $state['psr4Namespaces'];
344 }
345
346 }
347
348 spl_autoload_register( [ 'AutoLoader', 'autoload' ] );
349
350 // Load composer's autoloader if present
351 if ( is_readable( __DIR__ . '/../vendor/autoload.php' ) ) {
352 require_once __DIR__ . '/../vendor/autoload.php';
353 } elseif ( file_exists( __DIR__ . '/../vendor/autoload.php' ) ) {
354 die( __DIR__ . '/../vendor/autoload.php exists but is not readable' );
355 }