Completed
Branch master (e2eefa)
by
unknown
25:58
created

MediaWikiServices   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 424
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 5
Bugs 0 Features 2
Metric Value
dl 0
loc 424
rs 8.3999
c 5
b 0
f 2
wmc 38
lcom 1
cbo 5

26 Methods

Rating   Name   Duplication   Size   Complexity  
A getInstance() 0 12 2
A forceGlobalInstance() 0 10 2
A resetGlobalInstance() 0 16 3
A newInstance() 0 12 1
A disableStorageBackend() 0 9 2
A resetChildProcessServices() 0 9 1
A resetServiceForTesting() 0 7 3
B failIfResetNotAllowed() 0 10 6
A __construct() 0 8 1
A getBootstrapConfig() 0 3 1
A getConfigFactory() 0 3 1
A getMainConfig() 0 3 1
A getSiteLookup() 0 3 1
A getSiteStore() 0 3 1
A getStatsdDataFactory() 0 3 1
A getEventRelayerGroup() 0 3 1
A newSearchEngine() 0 4 1
A getSearchEngineFactory() 0 3 1
A getSearchEngineConfig() 0 3 1
A getSkinFactory() 0 3 1
A getDBLoadBalancerFactory() 0 3 1
A getDBLoadBalancer() 0 3 1
A getWatchedItemStore() 0 3 1
A getGenderCache() 0 3 1
A getTitleFormatter() 0 3 1
A getTitleParser() 0 3 1
1
<?php
2
namespace MediaWiki;
3
4
use Config;
5
use ConfigFactory;
6
use EventRelayerGroup;
7
use GenderCache;
8
use GlobalVarConfig;
9
use Hooks;
10
use LBFactory;
11
use Liuggio\StatsdClient\Factory\StatsdDataFactory;
12
use LoadBalancer;
13
use MediaWiki\Services\ServiceContainer;
14
use MWException;
15
use ResourceLoader;
16
use SearchEngine;
17
use SearchEngineConfig;
18
use SearchEngineFactory;
19
use SiteLookup;
20
use SiteStore;
21
use WatchedItemStore;
22
use SkinFactory;
23
use TitleFormatter;
24
use TitleParser;
25
26
/**
27
 * Service locator for MediaWiki core services.
28
 *
29
 * This program is free software; you can redistribute it and/or modify
30
 * it under the terms of the GNU General Public License as published by
31
 * the Free Software Foundation; either version 2 of the License, or
32
 * (at your option) any later version.
33
 *
34
 * This program is distributed in the hope that it will be useful,
35
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
36
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37
 * GNU General Public License for more details.
38
 *
39
 * You should have received a copy of the GNU General Public License along
40
 * with this program; if not, write to the Free Software Foundation, Inc.,
41
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
42
 * http://www.gnu.org/copyleft/gpl.html
43
 *
44
 * @file
45
 *
46
 * @since 1.27
47
 */
48
49
/**
50
 * MediaWikiServices is the service locator for the application scope of MediaWiki.
51
 * Its implemented as a simple configurable DI container.
52
 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
53
 * the network of service objects that defines MediaWiki's application logic.
54
 * It acts as an entry point to MediaWiki's dependency injection mechanism.
55
 *
56
 * Services are defined in the "wiring" array passed to the constructor,
57
 * or by calling defineService().
58
 *
59
 * @see docs/injection.txt for an overview of using dependency injection in the
60
 *      MediaWiki code base.
61
 */
62
class MediaWikiServices extends ServiceContainer {
63
64
	/**
65
	 * @var MediaWikiServices|null
66
	 */
67
	private static $instance = null;
68
69
	/**
70
	 * Returns the global default instance of the top level service locator.
71
	 *
72
	 * @since 1.27
73
	 *
74
	 * The default instance is initialized using the service instantiator functions
75
	 * defined in ServiceWiring.php.
76
	 *
77
	 * @note This should only be called by static functions! The instance returned here
78
	 * should not be passed around! Objects that need access to a service should have
79
	 * that service injected into the constructor, never a service locator!
80
	 *
81
	 * @return MediaWikiServices
82
	 */
83
	public static function getInstance() {
84
		if ( self::$instance === null ) {
85
			// NOTE: constructing GlobalVarConfig here is not particularly pretty,
86
			// but some information from the global scope has to be injected here,
87
			// even if it's just a file name or database credentials to load
88
			// configuration from.
89
			$bootstrapConfig = new GlobalVarConfig();
90
			self::$instance = self::newInstance( $bootstrapConfig );
91
		}
92
93
		return self::$instance;
94
	}
95
96
	/**
97
	 * Replaces the global MediaWikiServices instance.
98
	 *
99
	 * @since 1.28
100
	 *
101
	 * @note This is for use in PHPUnit tests only!
102
	 *
103
	 * @throws MWException if called outside of PHPUnit tests.
104
	 *
105
	 * @param MediaWikiServices $services The new MediaWikiServices object.
106
	 *
107
	 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
108
	 */
109
	public static function forceGlobalInstance( MediaWikiServices $services ) {
110
		if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
111
			throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
112
		}
113
114
		$old = self::getInstance();
115
		self::$instance = $services;
116
117
		return $old;
118
	}
119
120
	/**
121
	 * Creates a new instance of MediaWikiServices and sets it as the global default
122
	 * instance. getInstance() will return a different MediaWikiServices object
123
	 * after every call to resetGlobalServiceLocator().
124
	 *
125
	 * @since 1.28
126
	 *
127
	 * @warning This should not be used during normal operation. It is intended for use
128
	 * when the configuration has changed significantly since bootstrap time, e.g.
129
	 * during the installation process or during testing.
130
	 *
131
	 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
132
	 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
133
	 * any of the services managed by MediaWikiServices exist. If any service objects
134
	 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
135
	 * with the operation of the services managed by the new MediaWikiServices.
136
	 * Operating with a mix of services created by the old and the new
137
	 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
138
	 * Any class implementing LAZY LOADING is especially prone to this problem,
139
	 * since instances would typically retain a reference to a storage layer service.
140
	 *
141
	 * @see forceGlobalInstance()
142
	 * @see resetGlobalInstance()
143
	 * @see resetBetweenTest()
144
	 *
145
	 * @param Config|null $bootstrapConfig The Config object to be registered as the
146
	 *        'BootstrapConfig' service. This has to contain at least the information
147
	 *        needed to set up the 'ConfigFactory' service. If not given, the bootstrap
148
	 *        config of the old instance of MediaWikiServices will be re-used. If there
149
	 *        was no previous instance, a new GlobalVarConfig object will be used to
150
	 *        bootstrap the services.
151
	 *
152
	 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
153
	 *         Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
154
	 *          is defined).
155
	 */
156
	public static function resetGlobalInstance( Config $bootstrapConfig = null ) {
157
		if ( self::$instance === null ) {
158
			// no global instance yet, nothing to reset
159
			return;
160
		}
161
162
		self::failIfResetNotAllowed( __METHOD__ );
163
164
		if ( $bootstrapConfig === null ) {
165
			$bootstrapConfig = self::$instance->getBootstrapConfig();
166
		}
167
168
		self::$instance->destroy();
169
170
		self::$instance = self::newInstance( $bootstrapConfig );
171
	}
172
173
	/**
174
	 * Creates a new MediaWikiServices instance and initializes it according to the
175
	 * given $bootstrapConfig. In particular, all wiring files defined in the
176
	 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
177
	 *
178
	 * @param Config|null $bootstrapConfig The Config object to be registered as the
179
	 *        'BootstrapConfig' service. This has to contain at least the information
180
	 *        needed to set up the 'ConfigFactory' service. If not provided, any call
181
	 *        to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
182
	 *        A MediaWikiServices instance without access to configuration is called
183
	 *        "primordial".
184
	 *
185
	 * @return MediaWikiServices
186
	 * @throws MWException
187
	 */
188
	private static function newInstance( Config $bootstrapConfig ) {
189
		$instance = new self( $bootstrapConfig );
190
191
		// Load the default wiring from the specified files.
192
		$wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
193
		$instance->loadWiringFiles( $wiringFiles );
194
195
		// Provide a traditional hook point to allow extensions to configure services.
196
		Hooks::run( 'MediaWikiServices', [ $instance ] );
197
198
		return $instance;
199
	}
200
201
	/**
202
	 * Disables all storage layer services. After calling this, any attempt to access the
203
	 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
204
	 * operation.
205
	 *
206
	 * @since 1.28
207
	 *
208
	 * @warning This is intended for extreme situations only and should never be used
209
	 * while serving normal web requests. Legitimate use cases for this method include
210
	 * the installation process. Test fixtures may also use this, if the fixture relies
211
	 * on globalState.
212
	 *
213
	 * @see resetGlobalInstance()
214
	 * @see resetChildProcessServices()
215
	 */
216
	public static function disableStorageBackend() {
217
		// TODO: also disable some Caches, JobQueues, etc
218
		$destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
219
		$services = self::getInstance();
220
221
		foreach ( $destroy as $name ) {
222
			$services->disableService( $name );
223
		}
224
	}
225
226
	/**
227
	 * Resets any services that may have become stale after a child process
228
	 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
229
	 * to call this method from the parent process.
230
	 *
231
	 * @since 1.28
232
	 *
233
	 * @note This is intended for use in the context of process forking only!
234
	 *
235
	 * @see resetGlobalInstance()
236
	 * @see disableStorageBackend()
237
	 */
238
	public static function resetChildProcessServices() {
239
		// NOTE: for now, just reset everything. Since we don't know the interdependencies
240
		// between services, we can't do this more selectively at this time.
241
		self::resetGlobalInstance();
242
243
		// Child, reseed because there is no bug in PHP:
244
		// http://bugs.php.net/bug.php?id=42465
245
		mt_srand( getmypid() );
246
	}
247
248
	/**
249
	 * Resets the given service for testing purposes.
250
	 *
251
	 * @since 1.28
252
	 *
253
	 * @warning This is generally unsafe! Other services may still retain references
254
	 * to the stale service instance, leading to failures and inconsistencies. Subclasses
255
	 * may use this method to reset specific services under specific instances, but
256
	 * it should not be exposed to application logic.
257
	 *
258
	 * @note With proper dependency injection used throughout the codebase, this method
259
	 * should not be needed. It is provided to allow tests that pollute global service
260
	 * instances to clean up.
261
	 *
262
	 * @param string $name
263
	 * @param string $destroy Whether the service instance should be destroyed if it exists.
264
	 *        When set to false, any existing service instance will effectively be detached
265
	 *        from the container.
266
	 *
267
	 * @throws MWException if called outside of PHPUnit tests.
268
	 */
269
	public function resetServiceForTesting( $name, $destroy = true ) {
270
		if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
271
			throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
272
		}
273
274
		$this->resetService( $name, $destroy );
0 ignored issues
show
Bug introduced by
It seems like $destroy defined by parameter $destroy on line 269 can also be of type string; however, MediaWiki\Services\Servi...ntainer::resetService() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
275
	}
276
277
	/**
278
	 * Convenience method that throws an exception unless it is called during a phase in which
279
	 * resetting of global services is allowed. In general, services should not be reset
280
	 * individually, since that may introduce inconsistencies.
281
	 *
282
	 * @since 1.28
283
	 *
284
	 * This method will throw an exception if:
285
	 *
286
	 * - self::$resetInProgress is false (to allow all services to be reset together
287
	 *   via resetGlobalInstance)
288
	 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
289
	 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
290
	 *
291
	 * This method is intended to be used to safeguard against accidentally resetting
292
	 * global service instances that are not yet managed by MediaWikiServices. It is
293
	 * defined here in the MediaWikiServices services class to have a central place
294
	 * for managing service bootstrapping and resetting.
295
	 *
296
	 * @param string $method the name of the caller method, as given by __METHOD__.
297
	 *
298
	 * @throws MWException if called outside bootstrap mode.
299
	 *
300
	 * @see resetGlobalInstance()
301
	 * @see forceGlobalInstance()
302
	 * @see disableStorageBackend()
303
	 */
304
	public static function failIfResetNotAllowed( $method ) {
305
		if ( !defined( 'MW_PHPUNIT_TEST' )
306
			&& !defined( 'MW_PARSER_TEST' )
307
			&& !defined( 'MEDIAWIKI_INSTALL' )
308
			&& !defined( 'RUN_MAINTENANCE_IF_MAIN' )
309
			&& defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
310
		) {
311
			throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
312
		}
313
	}
314
315
	/**
316
	 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
317
	 *        This has to contain at least the information needed to set up the 'ConfigFactory'
318
	 *        service.
319
	 */
320
	public function __construct( Config $config ) {
321
		parent::__construct();
322
323
		// Register the given Config object as the bootstrap config service.
324
		$this->defineService( 'BootstrapConfig', function() use ( $config ) {
325
			return $config;
326
		} );
327
	}
328
329
	// CONVENIENCE GETTERS ////////////////////////////////////////////////////
330
331
	/**
332
	 * Returns the Config object containing the bootstrap configuration.
333
	 * Bootstrap configuration would typically include database credentials
334
	 * and other information that may be needed before the ConfigFactory
335
	 * service can be instantiated.
336
	 *
337
	 * @note This should only be used during bootstrapping, in particular
338
	 * when creating the MainConfig service. Application logic should
339
	 * use getMainConfig() to get a Config instances.
340
	 *
341
	 * @since 1.27
342
	 * @return Config
343
	 */
344
	public function getBootstrapConfig() {
345
		return $this->getService( 'BootstrapConfig' );
346
	}
347
348
	/**
349
	 * @since 1.27
350
	 * @return ConfigFactory
351
	 */
352
	public function getConfigFactory() {
353
		return $this->getService( 'ConfigFactory' );
354
	}
355
356
	/**
357
	 * Returns the Config object that provides configuration for MediaWiki core.
358
	 * This may or may not be the same object that is returned by getBootstrapConfig().
359
	 *
360
	 * @since 1.27
361
	 * @return Config
362
	 */
363
	public function getMainConfig() {
364
		return $this->getService( 'MainConfig' );
365
	}
366
367
	/**
368
	 * @since 1.27
369
	 * @return SiteLookup
370
	 */
371
	public function getSiteLookup() {
372
		return $this->getService( 'SiteLookup' );
373
	}
374
375
	/**
376
	 * @since 1.27
377
	 * @return SiteStore
378
	 */
379
	public function getSiteStore() {
380
		return $this->getService( 'SiteStore' );
381
	}
382
383
	/**
384
	 * @since 1.27
385
	 * @return StatsdDataFactory
386
	 */
387
	public function getStatsdDataFactory() {
388
		return $this->getService( 'StatsdDataFactory' );
389
	}
390
391
	/**
392
	 * @since 1.27
393
	 * @return EventRelayerGroup
394
	 */
395
	public function getEventRelayerGroup() {
396
		return $this->getService( 'EventRelayerGroup' );
397
	}
398
399
	/**
400
	 * @since 1.27
401
	 * @return SearchEngine
402
	 */
403
	public function newSearchEngine() {
404
		// New engine object every time, since they keep state
405
		return $this->getService( 'SearchEngineFactory' )->create();
406
	}
407
408
	/**
409
	 * @since 1.27
410
	 * @return SearchEngineFactory
411
	 */
412
	public function getSearchEngineFactory() {
413
		return $this->getService( 'SearchEngineFactory' );
414
	}
415
416
	/**
417
	 * @since 1.27
418
	 * @return SearchEngineConfig
419
	 */
420
	public function getSearchEngineConfig() {
421
		return $this->getService( 'SearchEngineConfig' );
422
	}
423
424
	/**
425
	 * @since 1.27
426
	 * @return SkinFactory
427
	 */
428
	public function getSkinFactory() {
429
		return $this->getService( 'SkinFactory' );
430
	}
431
432
	/**
433
	 * @since 1.28
434
	 * @return LBFactory
435
	 */
436
	public function getDBLoadBalancerFactory() {
437
		return $this->getService( 'DBLoadBalancerFactory' );
438
	}
439
440
	/**
441
	 * @since 1.28
442
	 * @return LoadBalancer The main DB load balancer for the local wiki.
443
	 */
444
	public function getDBLoadBalancer() {
445
		return $this->getService( 'DBLoadBalancer' );
446
	}
447
448
	/**
449
	 * @since 1.28
450
	 * @return WatchedItemStore
451
	 */
452
	public function getWatchedItemStore() {
453
		return $this->getService( 'WatchedItemStore' );
454
	}
455
456
	/**
457
	 * @since 1.28
458
	 * @return GenderCache
459
	 */
460
	public function getGenderCache() {
461
		return $this->getService( 'GenderCache' );
462
	}
463
	/**
464
	 * @since 1.28
465
	 * @return TitleFormatter
466
	 */
467
	public function getTitleFormatter() {
468
		return $this->getService( 'TitleFormatter' );
469
	}
470
471
	/**
472
	 * @since 1.28
473
	 * @return TitleParser
474
	 */
475
	public function getTitleParser() {
476
		return $this->getService( 'TitleParser' );
477
	}
478
479
	///////////////////////////////////////////////////////////////////////////
480
	// NOTE: When adding a service getter here, don't forget to add a test
481
	// case for it in MediaWikiServicesTest::provideGetters() and in
482
	// MediaWikiServicesTest::provideGetService()!
483
	///////////////////////////////////////////////////////////////////////////
484
485
}
486