Completed
Branch master (1b526b)
by
unknown
29:06
created

MediaWikiServices   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 409
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 4
Bugs 0 Features 1
Metric Value
dl 0
loc 409
rs 8.8
c 4
b 0
f 1
wmc 36
lcom 1
cbo 5

24 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
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
24
/**
25
 * Service locator for MediaWiki core services.
26
 *
27
 * This program is free software; you can redistribute it and/or modify
28
 * it under the terms of the GNU General Public License as published by
29
 * the Free Software Foundation; either version 2 of the License, or
30
 * (at your option) any later version.
31
 *
32
 * This program is distributed in the hope that it will be useful,
33
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
34
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
35
 * GNU General Public License for more details.
36
 *
37
 * You should have received a copy of the GNU General Public License along
38
 * with this program; if not, write to the Free Software Foundation, Inc.,
39
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
40
 * http://www.gnu.org/copyleft/gpl.html
41
 *
42
 * @file
43
 *
44
 * @since 1.27
45
 */
46
47
/**
48
 * MediaWikiServices is the service locator for the application scope of MediaWiki.
49
 * Its implemented as a simple configurable DI container.
50
 * MediaWikiServices acts as a top level factory/registry for top level services, and builds
51
 * the network of service objects that defines MediaWiki's application logic.
52
 * It acts as an entry point to MediaWiki's dependency injection mechanism.
53
 *
54
 * Services are defined in the "wiring" array passed to the constructor,
55
 * or by calling defineService().
56
 *
57
 * @see docs/injection.txt for an overview of using dependency injection in the
58
 *      MediaWiki code base.
59
 */
60
class MediaWikiServices extends ServiceContainer {
61
62
	/**
63
	 * @var MediaWikiServices|null
64
	 */
65
	private static $instance = null;
66
67
	/**
68
	 * Returns the global default instance of the top level service locator.
69
	 *
70
	 * @since 1.27
71
	 *
72
	 * The default instance is initialized using the service instantiator functions
73
	 * defined in ServiceWiring.php.
74
	 *
75
	 * @note This should only be called by static functions! The instance returned here
76
	 * should not be passed around! Objects that need access to a service should have
77
	 * that service injected into the constructor, never a service locator!
78
	 *
79
	 * @return MediaWikiServices
80
	 */
81
	public static function getInstance() {
82
		if ( self::$instance === null ) {
83
			// NOTE: constructing GlobalVarConfig here is not particularly pretty,
84
			// but some information from the global scope has to be injected here,
85
			// even if it's just a file name or database credentials to load
86
			// configuration from.
87
			$bootstrapConfig = new GlobalVarConfig();
88
			self::$instance = self::newInstance( $bootstrapConfig );
89
		}
90
91
		return self::$instance;
92
	}
93
94
	/**
95
	 * Replaces the global MediaWikiServices instance.
96
	 *
97
	 * @since 1.28
98
	 *
99
	 * @note This is for use in PHPUnit tests only!
100
	 *
101
	 * @throws MWException if called outside of PHPUnit tests.
102
	 *
103
	 * @param MediaWikiServices $services The new MediaWikiServices object.
104
	 *
105
	 * @return MediaWikiServices The old MediaWikiServices object, so it can be restored later.
106
	 */
107
	public static function forceGlobalInstance( MediaWikiServices $services ) {
108
		if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
109
			throw new MWException( __METHOD__ . ' must not be used outside unit tests.' );
110
		}
111
112
		$old = self::getInstance();
113
		self::$instance = $services;
114
115
		return $old;
116
	}
117
118
	/**
119
	 * Creates a new instance of MediaWikiServices and sets it as the global default
120
	 * instance. getInstance() will return a different MediaWikiServices object
121
	 * after every call to resetGlobalServiceLocator().
122
	 *
123
	 * @since 1.28
124
	 *
125
	 * @warning This should not be used during normal operation. It is intended for use
126
	 * when the configuration has changed significantly since bootstrap time, e.g.
127
	 * during the installation process or during testing.
128
	 *
129
	 * @warning Calling resetGlobalServiceLocator() may leave the application in an inconsistent
130
	 * state. Calling this is only safe under the ASSUMPTION that NO REFERENCE to
131
	 * any of the services managed by MediaWikiServices exist. If any service objects
132
	 * managed by the old MediaWikiServices instance remain in use, they may INTERFERE
133
	 * with the operation of the services managed by the new MediaWikiServices.
134
	 * Operating with a mix of services created by the old and the new
135
	 * MediaWikiServices instance may lead to INCONSISTENCIES and even DATA LOSS!
136
	 * Any class implementing LAZY LOADING is especially prone to this problem,
137
	 * since instances would typically retain a reference to a storage layer service.
138
	 *
139
	 * @see forceGlobalInstance()
140
	 * @see resetGlobalInstance()
141
	 * @see resetBetweenTest()
142
	 *
143
	 * @param Config|null $bootstrapConfig The Config object to be registered as the
144
	 *        'BootstrapConfig' service. This has to contain at least the information
145
	 *        needed to set up the 'ConfigFactory' service. If not given, the bootstrap
146
	 *        config of the old instance of MediaWikiServices will be re-used. If there
147
	 *        was no previous instance, a new GlobalVarConfig object will be used to
148
	 *        bootstrap the services.
149
	 *
150
	 * @throws MWException If called after MW_SERVICE_BOOTSTRAP_COMPLETE has been defined in
151
	 *         Setup.php (unless MW_PHPUNIT_TEST or MEDIAWIKI_INSTALL or RUN_MAINTENANCE_IF_MAIN
152
	 *          is defined).
153
	 */
154
	public static function resetGlobalInstance( Config $bootstrapConfig = null ) {
155
		if ( self::$instance === null ) {
156
			// no global instance yet, nothing to reset
157
			return;
158
		}
159
160
		self::failIfResetNotAllowed( __METHOD__ );
161
162
		if ( $bootstrapConfig === null ) {
163
			$bootstrapConfig = self::$instance->getBootstrapConfig();
164
		}
165
166
		self::$instance->destroy();
167
168
		self::$instance = self::newInstance( $bootstrapConfig );
169
	}
170
171
	/**
172
	 * Creates a new MediaWikiServices instance and initializes it according to the
173
	 * given $bootstrapConfig. In particular, all wiring files defined in the
174
	 * ServiceWiringFiles setting are loaded, and the MediaWikiServices hook is called.
175
	 *
176
	 * @param Config|null $bootstrapConfig The Config object to be registered as the
177
	 *        'BootstrapConfig' service. This has to contain at least the information
178
	 *        needed to set up the 'ConfigFactory' service. If not provided, any call
179
	 *        to getBootstrapConfig(), getConfigFactory, or getMainConfig will fail.
180
	 *        A MediaWikiServices instance without access to configuration is called
181
	 *        "primordial".
182
	 *
183
	 * @return MediaWikiServices
184
	 * @throws MWException
185
	 */
186
	private static function newInstance( Config $bootstrapConfig ) {
187
		$instance = new self( $bootstrapConfig );
188
189
		// Load the default wiring from the specified files.
190
		$wiringFiles = $bootstrapConfig->get( 'ServiceWiringFiles' );
191
		$instance->loadWiringFiles( $wiringFiles );
192
193
		// Provide a traditional hook point to allow extensions to configure services.
194
		Hooks::run( 'MediaWikiServices', [ $instance ] );
195
196
		return $instance;
197
	}
198
199
	/**
200
	 * Disables all storage layer services. After calling this, any attempt to access the
201
	 * storage layer will result in an error. Use resetGlobalInstance() to restore normal
202
	 * operation.
203
	 *
204
	 * @since 1.28
205
	 *
206
	 * @warning This is intended for extreme situations only and should never be used
207
	 * while serving normal web requests. Legitimate use cases for this method include
208
	 * the installation process. Test fixtures may also use this, if the fixture relies
209
	 * on globalState.
210
	 *
211
	 * @see resetGlobalInstance()
212
	 * @see resetChildProcessServices()
213
	 */
214
	public static function disableStorageBackend() {
215
		// TODO: also disable some Caches, JobQueues, etc
216
		$destroy = [ 'DBLoadBalancer', 'DBLoadBalancerFactory' ];
217
		$services = self::getInstance();
218
219
		foreach ( $destroy as $name ) {
220
			$services->disableService( $name );
221
		}
222
	}
223
224
	/**
225
	 * Resets any services that may have become stale after a child process
226
	 * returns from after pcntl_fork(). It's also safe, but generally unnecessary,
227
	 * to call this method from the parent process.
228
	 *
229
	 * @since 1.28
230
	 *
231
	 * @note This is intended for use in the context of process forking only!
232
	 *
233
	 * @see resetGlobalInstance()
234
	 * @see disableStorageBackend()
235
	 */
236
	public static function resetChildProcessServices() {
237
		// NOTE: for now, just reset everything. Since we don't know the interdependencies
238
		// between services, we can't do this more selectively at this time.
239
		self::resetGlobalInstance();
240
241
		// Child, reseed because there is no bug in PHP:
242
		// http://bugs.php.net/bug.php?id=42465
243
		mt_srand( getmypid() );
244
	}
245
246
	/**
247
	 * Resets the given service for testing purposes.
248
	 *
249
	 * @since 1.28
250
	 *
251
	 * @warning This is generally unsafe! Other services may still retain references
252
	 * to the stale service instance, leading to failures and inconsistencies. Subclasses
253
	 * may use this method to reset specific services under specific instances, but
254
	 * it should not be exposed to application logic.
255
	 *
256
	 * @note With proper dependency injection used throughout the codebase, this method
257
	 * should not be needed. It is provided to allow tests that pollute global service
258
	 * instances to clean up.
259
	 *
260
	 * @param string $name
261
	 * @param string $destroy Whether the service instance should be destroyed if it exists.
262
	 *        When set to false, any existing service instance will effectively be detached
263
	 *        from the container.
264
	 *
265
	 * @throws MWException if called outside of PHPUnit tests.
266
	 */
267
	public function resetServiceForTesting( $name, $destroy = true ) {
268
		if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
269
			throw new MWException( 'resetServiceForTesting() must not be used outside unit tests.' );
270
		}
271
272
		$this->resetService( $name, $destroy );
0 ignored issues
show
Bug introduced by
It seems like $destroy defined by parameter $destroy on line 267 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...
273
	}
274
275
	/**
276
	 * Convenience method that throws an exception unless it is called during a phase in which
277
	 * resetting of global services is allowed. In general, services should not be reset
278
	 * individually, since that may introduce inconsistencies.
279
	 *
280
	 * @since 1.28
281
	 *
282
	 * This method will throw an exception if:
283
	 *
284
	 * - self::$resetInProgress is false (to allow all services to be reset together
285
	 *   via resetGlobalInstance)
286
	 * - and MEDIAWIKI_INSTALL is not defined (to allow services to be reset during installation)
287
	 * - and MW_PHPUNIT_TEST is not defined (to allow services to be reset during testing)
288
	 *
289
	 * This method is intended to be used to safeguard against accidentally resetting
290
	 * global service instances that are not yet managed by MediaWikiServices. It is
291
	 * defined here in the MediaWikiServices services class to have a central place
292
	 * for managing service bootstrapping and resetting.
293
	 *
294
	 * @param string $method the name of the caller method, as given by __METHOD__.
295
	 *
296
	 * @throws MWException if called outside bootstrap mode.
297
	 *
298
	 * @see resetGlobalInstance()
299
	 * @see forceGlobalInstance()
300
	 * @see disableStorageBackend()
301
	 */
302
	public static function failIfResetNotAllowed( $method ) {
303
		if ( !defined( 'MW_PHPUNIT_TEST' )
304
			&& !defined( 'MW_PARSER_TEST' )
305
			&& !defined( 'MEDIAWIKI_INSTALL' )
306
			&& !defined( 'RUN_MAINTENANCE_IF_MAIN' )
307
			&& defined( 'MW_SERVICE_BOOTSTRAP_COMPLETE' )
308
		) {
309
			throw new MWException( $method . ' may only be called during bootstrapping and unit tests!' );
310
		}
311
	}
312
313
	/**
314
	 * @param Config $config The Config object to be registered as the 'BootstrapConfig' service.
315
	 *        This has to contain at least the information needed to set up the 'ConfigFactory'
316
	 *        service.
317
	 */
318
	public function __construct( Config $config ) {
319
		parent::__construct();
320
321
		// Register the given Config object as the bootstrap config service.
322
		$this->defineService( 'BootstrapConfig', function() use ( $config ) {
323
			return $config;
324
		} );
325
	}
326
327
	// CONVENIENCE GETTERS ////////////////////////////////////////////////////
328
329
	/**
330
	 * Returns the Config object containing the bootstrap configuration.
331
	 * Bootstrap configuration would typically include database credentials
332
	 * and other information that may be needed before the ConfigFactory
333
	 * service can be instantiated.
334
	 *
335
	 * @note This should only be used during bootstrapping, in particular
336
	 * when creating the MainConfig service. Application logic should
337
	 * use getMainConfig() to get a Config instances.
338
	 *
339
	 * @since 1.27
340
	 * @return Config
341
	 */
342
	public function getBootstrapConfig() {
343
		return $this->getService( 'BootstrapConfig' );
344
	}
345
346
	/**
347
	 * @since 1.27
348
	 * @return ConfigFactory
349
	 */
350
	public function getConfigFactory() {
351
		return $this->getService( 'ConfigFactory' );
352
	}
353
354
	/**
355
	 * Returns the Config object that provides configuration for MediaWiki core.
356
	 * This may or may not be the same object that is returned by getBootstrapConfig().
357
	 *
358
	 * @since 1.27
359
	 * @return Config
360
	 */
361
	public function getMainConfig() {
362
		return $this->getService( 'MainConfig' );
363
	}
364
365
	/**
366
	 * @since 1.27
367
	 * @return SiteLookup
368
	 */
369
	public function getSiteLookup() {
370
		return $this->getService( 'SiteLookup' );
371
	}
372
373
	/**
374
	 * @since 1.27
375
	 * @return SiteStore
376
	 */
377
	public function getSiteStore() {
378
		return $this->getService( 'SiteStore' );
379
	}
380
381
	/**
382
	 * @since 1.27
383
	 * @return StatsdDataFactory
384
	 */
385
	public function getStatsdDataFactory() {
386
		return $this->getService( 'StatsdDataFactory' );
387
	}
388
389
	/**
390
	 * @since 1.27
391
	 * @return EventRelayerGroup
392
	 */
393
	public function getEventRelayerGroup() {
394
		return $this->getService( 'EventRelayerGroup' );
395
	}
396
397
	/**
398
	 * @since 1.27
399
	 * @return SearchEngine
400
	 */
401
	public function newSearchEngine() {
402
		// New engine object every time, since they keep state
403
		return $this->getService( 'SearchEngineFactory' )->create();
404
	}
405
406
	/**
407
	 * @since 1.27
408
	 * @return SearchEngineFactory
409
	 */
410
	public function getSearchEngineFactory() {
411
		return $this->getService( 'SearchEngineFactory' );
412
	}
413
414
	/**
415
	 * @since 1.27
416
	 * @return SearchEngineConfig
417
	 */
418
	public function getSearchEngineConfig() {
419
		return $this->getService( 'SearchEngineConfig' );
420
	}
421
422
	/**
423
	 * @since 1.27
424
	 * @return SkinFactory
425
	 */
426
	public function getSkinFactory() {
427
		return $this->getService( 'SkinFactory' );
428
	}
429
430
	/**
431
	 * @since 1.28
432
	 * @return LBFactory
433
	 */
434
	public function getDBLoadBalancerFactory() {
435
		return $this->getService( 'DBLoadBalancerFactory' );
436
	}
437
438
	/**
439
	 * @since 1.28
440
	 * @return LoadBalancer The main DB load balancer for the local wiki.
441
	 */
442
	public function getDBLoadBalancer() {
443
		return $this->getService( 'DBLoadBalancer' );
444
	}
445
446
	/**
447
	 * @since 1.28
448
	 * @return WatchedItemStore
449
	 */
450
	public function getWatchedItemStore() {
451
		return $this->getService( 'WatchedItemStore' );
452
	}
453
454
	/**
455
	 * @since 1.28
456
	 * @return GenderCache
457
	 */
458
	public function getGenderCache() {
459
		return $this->getService( 'GenderCache' );
460
	}
461
462
	///////////////////////////////////////////////////////////////////////////
463
	// NOTE: When adding a service getter here, don't forget to add a test
464
	// case for it in MediaWikiServicesTest::provideGetters() and in
465
	// MediaWikiServicesTest::provideGetService()!
466
	///////////////////////////////////////////////////////////////////////////
467
468
}
469