Drupal.php 22.6 KB
Newer Older
1
2
3
4
<?php

/**
 * @file
5
 * Contains \Drupal.
6
7
 */

8
use Drupal\Core\DependencyInjection\ContainerNotInitializedException;
9
use Symfony\Component\DependencyInjection\ContainerInterface;
10
11
12
13
14
15
16
17
18
19
20
21
22

/**
 * Static Service Container wrapper.
 *
 * Generally, code in Drupal should accept its dependencies via either
 * constructor injection or setter method injection. However, there are cases,
 * particularly in legacy procedural code, where that is infeasible. This
 * class acts as a unified global accessor to arbitrary services within the
 * system in order to ease the transition from procedural code to injected OO
 * code.
 *
 * The container is built by the kernel and passed in to this class which stores
 * it statically. The container always contains the services from
23
24
 * \Drupal\Core\CoreServiceProvider, the service providers of enabled modules and any other
 * service providers defined in $GLOBALS['conf']['container_service_providers'].
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 *
 * This class exists only to support legacy code that cannot be dependency
 * injected. If your code needs it, consider refactoring it to be object
 * oriented, if possible. When this is not possible, for instance in the case of
 * hook implementations, and your code is more than a few non-reusable lines, it
 * is recommended to instantiate an object implementing the actual logic.
 *
 * @code
 *   // Legacy procedural code.
 *   function hook_do_stuff() {
 *     $lock = lock()->acquire('stuff_lock');
 *     // ...
 *   }
 *
 *   // Correct procedural code.
 *   function hook_do_stuff() {
41
 *     $lock = \Drupal::lock()->acquire('stuff_lock');
42
43
44
45
46
47
 *     // ...
 *   }
 *
 *   // The preferred way: dependency injected code.
 *   function hook_do_stuff() {
 *     // Move the actual implementation to a class and instantiate it.
48
 *     $instance = new StuffDoingClass(\Drupal::lock());
49
50
51
52
53
54
 *     $instance->doStuff();
 *
 *     // Or, even better, rely on the service container to avoid hard coding a
 *     // specific interface implementation, so that the actual logic can be
 *     // swapped. This might not always make sense, but in general it is a good
 *     // practice.
55
 *     \Drupal::service('stuff.doing')->doStuff();
56
57
58
59
60
61
62
63
64
 *   }
 *
 *   interface StuffDoingInterface {
 *     public function doStuff();
 *   }
 *
 *   class StuffDoingClass implements StuffDoingInterface {
 *     protected $lockBackend;
 *
65
66
 *     public function __construct(LockBackendInterface $lock_backend) {
 *       $this->lockBackend = $lock_backend;
67
68
69
70
71
72
73
74
75
76
77
78
79
 *     }
 *
 *     public function doStuff() {
 *       $lock = $this->lockBackend->acquire('stuff_lock');
 *       // ...
 *     }
 *   }
 * @endcode
 *
 * @see \Drupal\Core\DrupalKernel
 */
class Drupal {

80
81
82
  /**
   * The current system version.
   */
xjm's avatar
xjm committed
83
  const VERSION = '9.2.0-dev';
84
85
86
87
88
89

  /**
   * Core API compatibility.
   */
  const CORE_COMPATIBILITY = '8.x';

90
91
92
93
94
  /**
   * Core minimum schema version.
   */
  const CORE_MINIMUM_SCHEMA_VERSION = 8000;

95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
  /**
   * Minimum supported version of PHP.
   *
   * Below this version:
   * - New sites cannot be installed, except from within tests.
   * - Updates from previous Drupal versions can be run, but users are warned
   *   that Drupal no longer supports that PHP version.
   * - An error is shown in the status report that the PHP version is too old.
   */
  const MINIMUM_SUPPORTED_PHP = '7.3.0';

  /**
   * Minimum allowed version of PHP for Drupal to be bootstrapped.
   *
   * Below this version:
   * - The installer cannot be run.
   * - Updates cannot be run.
   * - Modules and themes cannot be enabled.
   * - If a site managed to bypass all of the above, then an error is shown in
   *   the status report and various fatal errors occur on various pages.
   *
   * Note: To prevent the installer from having fatal errors on older versions
   * of PHP, the value of this constant is hardcoded twice in core/install.php:
   * - Once as a parameter of version_compare()
   * - Once in the error message printed to the user immediately after.
   * Remember to update both whenever this constant is updated.
   */
  const MINIMUM_PHP = '7.3.0';

  /**
   * Minimum recommended value of PHP memory_limit.
   *
   * 64M was chosen as a minimum requirement in order to allow for additional
   * contributed modules to be installed prior to hitting the limit. However,
   * 40M is the target for the Standard installation profile.
   */
  const MINIMUM_PHP_MEMORY_LIMIT = '64M';

  /**
   * Minimum recommended version of PHP.
   *
   * Sites installing Drupal on PHP versions lower than this will see a warning
   * message, but Drupal can still be installed. Used for (e.g.) PHP versions
   * that have reached their EOL or will in the near future.
   */
  const RECOMMENDED_PHP = '7.3';

142
  /**
143
   * The currently active container object, or NULL if not initialized yet.
144
   *
145
   * @var \Symfony\Component\DependencyInjection\ContainerInterface|null
146
147
148
149
150
151
152
   */
  protected static $container;

  /**
   * Sets a new global container.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
153
   *   A new container instance to replace the current.
154
   */
155
  public static function setContainer(ContainerInterface $container) {
156
157
158
    static::$container = $container;
  }

159
160
161
162
163
164
165
  /**
   * Unsets the global container.
   */
  public static function unsetContainer() {
    static::$container = NULL;
  }

166
167
168
  /**
   * Returns the currently active global container.
   *
169
   * @return \Symfony\Component\DependencyInjection\ContainerInterface
170
171
   *
   * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException
172
173
   */
  public static function getContainer() {
174
175
176
    if (static::$container === NULL) {
      throw new ContainerNotInitializedException('\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.');
    }
177
178
179
    return static::$container;
  }

180
181
182
183
184
185
186
187
188
  /**
   * Returns TRUE if the container has been initialized, FALSE otherwise.
   *
   * @return bool
   */
  public static function hasContainer() {
    return static::$container !== NULL;
  }

189
190
191
192
193
194
195
196
197
  /**
   * Retrieves a service from the container.
   *
   * Use this method if the desired service is not one of those with a dedicated
   * accessor method below. If it is listed below, those methods are preferred
   * as they can return useful type hints.
   *
   * @param string $id
   *   The ID of the service to retrieve.
198
   *
199
200
201
202
   * @return mixed
   *   The specified service.
   */
  public static function service($id) {
203
    return static::getContainer()->get($id);
204
205
  }

206
207
208
209
210
211
212
213
214
215
  /**
   * Indicates if a service is defined in the container.
   *
   * @param string $id
   *   The ID of the service to check.
   *
   * @return bool
   *   TRUE if the specified service exists, FALSE otherwise.
   */
  public static function hasService($id) {
216
217
    // Check hasContainer() first in order to always return a Boolean.
    return static::hasContainer() && static::getContainer()->has($id);
218
219
  }

220
221
222
223
224
225
  /**
   * Gets the app root.
   *
   * @return string
   */
  public static function root() {
226
    return static::getContainer()->getParameter('app.root');
227
228
  }

229
230
231
232
233
234
235
236
237
238
  /**
   * Gets the active install profile.
   *
   * @return string|null
   *   The name of the active install profile.
   */
  public static function installProfile() {
    return static::getContainer()->getParameter('install_profile');
  }

239
240
241
242
243
244
245
  /**
   * Indicates if there is a currently active request object.
   *
   * @return bool
   *   TRUE if there is a currently active request object, FALSE otherwise.
   */
  public static function hasRequest() {
246
247
    // Check hasContainer() first in order to always return a Boolean.
    return static::hasContainer() && static::getContainer()->has('request_stack') && static::getContainer()->get('request_stack')->getCurrentRequest() !== NULL;
248
249
  }

250
251
252
  /**
   * Retrieves the currently active request object.
   *
253
   * Note: The use of this wrapper in particular is especially discouraged. Most
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
   * code should not need to access the request directly.  Doing so means it
   * will only function when handling an HTTP request, and will require special
   * modification or wrapping when run from a command line tool, from certain
   * queue processors, or from automated tests.
   *
   * If code must access the request, it is considerably better to register
   * an object with the Service Container and give it a setRequest() method
   * that is configured to run when the service is created.  That way, the
   * correct request object can always be provided by the container and the
   * service can still be unit tested.
   *
   * If this method must be used, never save the request object that is
   * returned.  Doing so may lead to inconsistencies as the request object is
   * volatile and may change at various times, such as during a subrequest.
   *
   * @return \Symfony\Component\HttpFoundation\Request
   *   The currently active request object.
   */
  public static function request() {
273
    return static::getContainer()->get('request_stack')->getCurrentRequest();
274
275
  }

276
  /**
277
   * Retrieves the request stack.
278
279
280
281
282
   *
   * @return \Symfony\Component\HttpFoundation\RequestStack
   *   The request stack
   */
  public static function requestStack() {
283
    return static::getContainer()->get('request_stack');
284
285
  }

286
287
288
289
290
291
292
  /**
   * Retrieves the currently active route match object.
   *
   * @return \Drupal\Core\Routing\RouteMatchInterface
   *   The currently active route match object.
   */
  public static function routeMatch() {
293
    return static::getContainer()->get('current_route_match');
294
295
  }

296
297
298
  /**
   * Gets the current active user.
   *
299
300
301
302
303
304
305
   * This method will return the \Drupal\Core\Session\AccountProxy object of the
   * current user. You can use the \Drupal\user\Entity\User::load() method to
   * load the full user entity object. For example:
   * @code
   *   $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
   * @endcode
   *
306
   * @return \Drupal\Core\Session\AccountProxyInterface
307
308
   */
  public static function currentUser() {
309
    return static::getContainer()->get('current_user');
310
311
  }

312
313
314
315
316
317
318
319
320
321
  /**
   * Retrieves the entity type manager.
   *
   * @return \Drupal\Core\Entity\EntityTypeManagerInterface
   *   The entity type manager.
   */
  public static function entityTypeManager() {
    return static::getContainer()->get('entity_type.manager');
  }

322
323
324
325
326
327
328
  /**
   * Returns the current primary database.
   *
   * @return \Drupal\Core\Database\Connection
   *   The current active database's master connection.
   */
  public static function database() {
329
    return static::getContainer()->get('database');
330
331
  }

332
333
334
335
336
  /**
   * Returns the requested cache bin.
   *
   * @param string $bin
   *   (optional) The cache bin for which the cache object should be returned,
337
   *   defaults to 'default'.
338
   *
339
   * @return \Drupal\Core\Cache\CacheBackendInterface
340
   *   The cache object associated with the specified bin.
341
342
   *
   * @ingroup cache
343
   */
344
  public static function cache($bin = 'default') {
345
    return static::getContainer()->get('cache.' . $bin);
346
347
  }

348
349
350
351
352
353
354
355
356
357
  /**
   * Retrieves the class resolver.
   *
   * This is to be used in procedural code such as module files to instantiate
   * an object of a class that implements
   * \Drupal\Core\DependencyInjection\ContainerInjectionInterface.
   *
   * One common usecase is to provide a class which contains the actual code
   * of a hook implementation, without having to create a service.
   *
358
359
360
361
362
363
364
365
366
   * @param string $class
   *   (optional) A class name to instantiate.
   *
   * @return \Drupal\Core\DependencyInjection\ClassResolverInterface|object
   *   The class resolver or if $class is provided, a class instance with a
   *   given class definition.
   *
   * @throws \InvalidArgumentException
   *   If $class does not exist.
367
   */
368
369
370
371
  public static function classResolver($class = NULL) {
    if ($class) {
      return static::getContainer()->get('class_resolver')->getInstanceFromDefinition($class);
    }
372
373
374
    return static::getContainer()->get('class_resolver');
  }

375
376
377
378
379
380
381
382
383
384
  /**
   * Returns an expirable key value store collection.
   *
   * @param string $collection
   *   The name of the collection holding key and value pairs.
   *
   * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
   *   An expirable key value store collection.
   */
  public static function keyValueExpirable($collection) {
385
    return static::getContainer()->get('keyvalue.expirable')->get($collection);
386
387
  }

388
389
390
391
  /**
   * Returns the locking layer instance.
   *
   * @return \Drupal\Core\Lock\LockBackendInterface
392
393
   *
   * @ingroup lock
394
395
   */
  public static function lock() {
396
    return static::getContainer()->get('lock');
397
398
  }

399
400
401
402
  /**
   * Retrieves a configuration object.
   *
   * This is the main entry point to the configuration API. Calling
403
   * @code \Drupal::config('book.admin') @endcode will return a configuration
404
   * object the Book module can use to read its administrative settings.
405
406
   *
   * @param string $name
407
408
409
410
411
   *   The name of the configuration object to retrieve, which typically
   *   corresponds to a configuration file. For
   *   @code \Drupal::config('book.admin') @endcode, the configuration
   *   object returned will contain the content of the book.admin
   *   configuration file.
412
   *
413
414
   * @return \Drupal\Core\Config\ImmutableConfig
   *   An immutable configuration object.
415
416
   */
  public static function config($name) {
417
    return static::getContainer()->get('config.factory')->get($name);
418
419
  }

420
421
422
423
424
425
426
  /**
   * Retrieves the configuration factory.
   *
   * This is mostly used to change the override settings on the configuration
   * factory. For example, changing the language, or turning all overrides on
   * or off.
   *
427
   * @return \Drupal\Core\Config\ConfigFactoryInterface
428
   *   The configuration factory service.
429
430
   */
  public static function configFactory() {
431
    return static::getContainer()->get('config.factory');
432
433
  }

434
435
436
  /**
   * Returns a queue for the given queue name.
   *
437
438
439
440
441
442
443
444
   * The following values can be set in your settings.php file's $settings
   * array to define which services are used for queues:
   * - queue_reliable_service_$name: The container service to use for the
   *   reliable queue $name.
   * - queue_service_$name: The container service to use for the
   *   queue $name.
   * - queue_default: The container service to use by default for queues
   *   without overrides. This defaults to 'queue.database'.
445
446
447
448
449
450
451
452
453
454
455
456
   *
   * @param string $name
   *   The name of the queue to work with.
   * @param bool $reliable
   *   (optional) TRUE if the ordering of items and guaranteeing every item
   *   executes at least once is important, FALSE if scalability is the main
   *   concern. Defaults to FALSE.
   *
   * @return \Drupal\Core\Queue\QueueInterface
   *   The queue object for a given name.
   */
  public static function queue($name, $reliable = FALSE) {
457
    return static::getContainer()->get('queue')->get($name, $reliable);
458
459
460
461
462
  }

  /**
   * Returns a key/value storage collection.
   *
463
   * @param string $collection
464
465
466
467
468
   *   Name of the key/value collection to return.
   *
   * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  public static function keyValue($collection) {
469
    return static::getContainer()->get('keyvalue')->get($collection);
470
471
472
473
474
475
476
477
478
  }

  /**
   * Returns the state storage service.
   *
   * Use this to store machine-generated data, local to a specific environment
   * that does not need deploying and does not need human editing; for example,
   * the last time cron was run. Data which needs to be edited by humans and
   * needs to be the same across development, production, etc. environments
479
   * (for example, the system maintenance message) should use \Drupal::config() instead.
480
   *
481
   * @return \Drupal\Core\State\StateInterface
482
483
   */
  public static function state() {
484
    return static::getContainer()->get('state');
485
486
487
488
489
  }

  /**
   * Returns the default http client.
   *
490
   * @return \GuzzleHttp\Client
491
492
493
   *   A guzzle http client instance.
   */
  public static function httpClient() {
494
    return static::getContainer()->get('http_client');
495
496
497
498
499
500
  }

  /**
   * Returns the entity query object for this entity type.
   *
   * @param string $entity_type
501
   *   The entity type (for example, node) for which the query object should be
502
503
   *   returned.
   * @param string $conjunction
504
505
   *   (optional) Either 'AND' if all conditions in the query need to apply, or
   *   'OR' if any of them is sufficient. Defaults to 'AND'.
506
507
508
509
510
   *
   * @return \Drupal\Core\Entity\Query\QueryInterface
   *   The query object that can query the given entity type.
   */
  public static function entityQuery($entity_type, $conjunction = 'AND') {
511
    return static::entityTypeManager()->getStorage($entity_type)->getQuery($conjunction);
512
513
  }

514
515
516
  /**
   * Returns the entity query aggregate object for this entity type.
   *
517
   * @param string $entity_type
518
   *   The entity type (for example, node) for which the query object should be
519
   *   returned.
520
   * @param string $conjunction
521
522
   *   (optional) Either 'AND' if all conditions in the query need to apply, or
   *   'OR' if any of them is sufficient. Defaults to 'AND'.
523
   *
524
   * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
525
526
527
   *   The query object that can query the given entity type.
   */
  public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
528
    return static::entityTypeManager()->getStorage($entity_type)->getAggregateQuery($conjunction);
529
530
  }

531
532
533
534
535
536
  /**
   * Returns the flood instance.
   *
   * @return \Drupal\Core\Flood\FloodInterface
   */
  public static function flood() {
537
    return static::getContainer()->get('flood');
538
539
540
541
542
  }

  /**
   * Returns the module handler.
   *
543
   * @return \Drupal\Core\Extension\ModuleHandlerInterface
544
545
   */
  public static function moduleHandler() {
546
    return static::getContainer()->get('module_handler');
547
548
549
550
551
552
553
  }

  /**
   * Returns the typed data manager service.
   *
   * Use the typed data manager service for creating typed data objects.
   *
554
   * @return \Drupal\Core\TypedData\TypedDataManagerInterface
555
556
557
558
   *   The typed data manager.
   *
   * @see \Drupal\Core\TypedData\TypedDataManager::create()
   */
559
  public static function typedDataManager() {
560
    return static::getContainer()->get('typed_data_manager');
561
562
  }

563
564
565
566
567
568
569
  /**
   * Returns the token service.
   *
   * @return \Drupal\Core\Utility\Token
   *   The token service.
   */
  public static function token() {
570
    return static::getContainer()->get('token');
571
572
  }

573
574
575
  /**
   * Returns the url generator service.
   *
576
   * @return \Drupal\Core\Routing\UrlGeneratorInterface
577
578
579
   *   The url generator service.
   */
  public static function urlGenerator() {
580
    return static::getContainer()->get('url_generator');
581
582
583
584
585
586
587
588
  }

  /**
   * Returns the link generator service.
   *
   * @return \Drupal\Core\Utility\LinkGeneratorInterface
   */
  public static function linkGenerator() {
589
    return static::getContainer()->get('link_generator');
590
591
  }

592
593
594
  /**
   * Returns the string translation service.
   *
595
   * @return \Drupal\Core\StringTranslation\TranslationManager
596
597
598
   *   The string translation manager.
   */
  public static function translation() {
599
    return static::getContainer()->get('string_translation');
600
601
  }

602
603
604
  /**
   * Returns the language manager service.
   *
605
   * @return \Drupal\Core\Language\LanguageManagerInterface
606
607
608
   *   The language manager.
   */
  public static function languageManager() {
609
    return static::getContainer()->get('language_manager');
610
611
  }

612
613
614
  /**
   * Returns the CSRF token manager service.
   *
615
616
617
618
619
   * The generated token is based on the session ID of the current user. Normally,
   * anonymous users do not have a session, so the generated token will be
   * different on every page request. To generate a token for users without a
   * session, manually start a session prior to calling this function.
   *
620
621
   * @return \Drupal\Core\Access\CsrfTokenGenerator
   *   The CSRF token manager.
622
   *
623
   * @see \Drupal\Core\Session\SessionManager::start()
624
625
   */
  public static function csrfToken() {
626
    return static::getContainer()->get('csrf_token');
627
628
  }

629
630
631
  /**
   * Returns the transliteration service.
   *
632
   * @return \Drupal\Core\Transliteration\PhpTransliteration
633
634
635
   *   The transliteration manager.
   */
  public static function transliteration() {
636
    return static::getContainer()->get('transliteration');
637
638
  }

639
640
641
642
643
644
645
  /**
   * Returns the form builder service.
   *
   * @return \Drupal\Core\Form\FormBuilderInterface
   *   The form builder.
   */
  public static function formBuilder() {
646
    return static::getContainer()->get('form_builder');
647
648
  }

649
650
651
652
653
654
  /**
   * Gets the theme service.
   *
   * @return \Drupal\Core\Theme\ThemeManagerInterface
   */
  public static function theme() {
655
    return static::getContainer()->get('theme.manager');
656
657
  }

658
659
660
661
662
663
  /**
   * Gets the syncing state.
   *
   * @return bool
   *   Returns TRUE is syncing flag set.
   */
664
  public static function isConfigSyncing() {
665
    return static::getContainer()->get('config.installer')->isSyncing();
666
667
  }

668
669
670
671
672
673
674
  /**
   * Returns a channel logger object.
   *
   * @param string $channel
   *   The name of the channel. Can be any string, but the general practice is
   *   to use the name of the subsystem calling this.
   *
675
   * @return \Psr\Log\LoggerInterface
676
677
678
   *   The logger for this channel.
   */
  public static function logger($channel) {
679
    return static::getContainer()->get('logger.factory')->get($channel);
680
681
  }

682
683
684
685
686
687
688
  /**
   * Returns the menu tree.
   *
   * @return \Drupal\Core\Menu\MenuLinkTreeInterface
   *   The menu tree.
   */
  public static function menuTree() {
689
    return static::getContainer()->get('menu.link_tree');
690
691
  }

692
693
694
695
696
697
  /**
   * Returns the path validator.
   *
   * @return \Drupal\Core\Path\PathValidatorInterface
   */
  public static function pathValidator() {
698
    return static::getContainer()->get('path.validator');
699
700
  }

701
702
703
704
705
706
707
  /**
   * Returns the access manager service.
   *
   * @return \Drupal\Core\Access\AccessManagerInterface
   *   The access manager service.
   */
  public static function accessManager() {
708
    return static::getContainer()->get('access_manager');
709
710
  }

711
712
713
714
715
716
717
718
719
720
  /**
   * Returns the redirect destination helper.
   *
   * @return \Drupal\Core\Routing\RedirectDestinationInterface
   *   The redirect destination helper.
   */
  public static function destination() {
    return static::getContainer()->get('redirect.destination');
  }

721
722
723
724
725
726
727
728
729
730
  /**
   * Returns the entity definition update manager.
   *
   * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
   *   The entity definition update manager.
   */
  public static function entityDefinitionUpdateManager() {
    return static::getContainer()->get('entity.definition_update_manager');
  }

731
732
733
734
735
736
737
738
739
740
  /**
   * Returns the time service.
   *
   * @return \Drupal\Component\Datetime\TimeInterface
   *   The time service.
   */
  public static function time() {
    return static::getContainer()->get('datetime.time');
  }

741
742
743
744
745
746
747
  /**
   * Returns the messenger.
   *
   * @return \Drupal\Core\Messenger\MessengerInterface
   *   The messenger.
   */
  public static function messenger() {
748
    return static::getContainer()->get('messenger');
749
750
  }

751
}