ebd52afbaa2d7826e2220849cc62bc40f67289df
[yaffs-website] / web / core / lib / Drupal.php
1 <?php
2
3 /**
4  * @file
5  * Contains \Drupal.
6  */
7
8 use Drupal\Core\DependencyInjection\ContainerNotInitializedException;
9 use Drupal\Core\Messenger\LegacyMessenger;
10 use Drupal\Core\Url;
11 use Symfony\Component\DependencyInjection\ContainerInterface;
12
13 /**
14  * Static Service Container wrapper.
15  *
16  * Generally, code in Drupal should accept its dependencies via either
17  * constructor injection or setter method injection. However, there are cases,
18  * particularly in legacy procedural code, where that is infeasible. This
19  * class acts as a unified global accessor to arbitrary services within the
20  * system in order to ease the transition from procedural code to injected OO
21  * code.
22  *
23  * The container is built by the kernel and passed in to this class which stores
24  * it statically. The container always contains the services from
25  * \Drupal\Core\CoreServiceProvider, the service providers of enabled modules and any other
26  * service providers defined in $GLOBALS['conf']['container_service_providers'].
27  *
28  * This class exists only to support legacy code that cannot be dependency
29  * injected. If your code needs it, consider refactoring it to be object
30  * oriented, if possible. When this is not possible, for instance in the case of
31  * hook implementations, and your code is more than a few non-reusable lines, it
32  * is recommended to instantiate an object implementing the actual logic.
33  *
34  * @code
35  *   // Legacy procedural code.
36  *   function hook_do_stuff() {
37  *     $lock = lock()->acquire('stuff_lock');
38  *     // ...
39  *   }
40  *
41  *   // Correct procedural code.
42  *   function hook_do_stuff() {
43  *     $lock = \Drupal::lock()->acquire('stuff_lock');
44  *     // ...
45  *   }
46  *
47  *   // The preferred way: dependency injected code.
48  *   function hook_do_stuff() {
49  *     // Move the actual implementation to a class and instantiate it.
50  *     $instance = new StuffDoingClass(\Drupal::lock());
51  *     $instance->doStuff();
52  *
53  *     // Or, even better, rely on the service container to avoid hard coding a
54  *     // specific interface implementation, so that the actual logic can be
55  *     // swapped. This might not always make sense, but in general it is a good
56  *     // practice.
57  *     \Drupal::service('stuff.doing')->doStuff();
58  *   }
59  *
60  *   interface StuffDoingInterface {
61  *     public function doStuff();
62  *   }
63  *
64  *   class StuffDoingClass implements StuffDoingInterface {
65  *     protected $lockBackend;
66  *
67  *     public function __construct(LockBackendInterface $lock_backend) {
68  *       $this->lockBackend = $lock_backend;
69  *     }
70  *
71  *     public function doStuff() {
72  *       $lock = $this->lockBackend->acquire('stuff_lock');
73  *       // ...
74  *     }
75  *   }
76  * @endcode
77  *
78  * @see \Drupal\Core\DrupalKernel
79  */
80 class Drupal {
81
82   /**
83    * The current system version.
84    */
85   const VERSION = '8.6.3';
86
87   /**
88    * Core API compatibility.
89    */
90   const CORE_COMPATIBILITY = '8.x';
91
92   /**
93    * Core minimum schema version.
94    */
95   const CORE_MINIMUM_SCHEMA_VERSION = 8000;
96
97   /**
98    * The currently active container object, or NULL if not initialized yet.
99    *
100    * @var \Symfony\Component\DependencyInjection\ContainerInterface|null
101    */
102   protected static $container;
103
104   /**
105    * Sets a new global container.
106    *
107    * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
108    *   A new container instance to replace the current.
109    */
110   public static function setContainer(ContainerInterface $container) {
111     static::$container = $container;
112   }
113
114   /**
115    * Unsets the global container.
116    */
117   public static function unsetContainer() {
118     static::$container = NULL;
119   }
120
121   /**
122    * Returns the currently active global container.
123    *
124    * @return \Symfony\Component\DependencyInjection\ContainerInterface|null
125    *
126    * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException
127    */
128   public static function getContainer() {
129     if (static::$container === NULL) {
130       throw new ContainerNotInitializedException('\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.');
131     }
132     return static::$container;
133   }
134
135   /**
136    * Returns TRUE if the container has been initialized, FALSE otherwise.
137    *
138    * @return bool
139    */
140   public static function hasContainer() {
141     return static::$container !== NULL;
142   }
143
144   /**
145    * Retrieves a service from the container.
146    *
147    * Use this method if the desired service is not one of those with a dedicated
148    * accessor method below. If it is listed below, those methods are preferred
149    * as they can return useful type hints.
150    *
151    * @param string $id
152    *   The ID of the service to retrieve.
153    *
154    * @return mixed
155    *   The specified service.
156    */
157   public static function service($id) {
158     return static::getContainer()->get($id);
159   }
160
161   /**
162    * Indicates if a service is defined in the container.
163    *
164    * @param string $id
165    *   The ID of the service to check.
166    *
167    * @return bool
168    *   TRUE if the specified service exists, FALSE otherwise.
169    */
170   public static function hasService($id) {
171     // Check hasContainer() first in order to always return a Boolean.
172     return static::hasContainer() && static::getContainer()->has($id);
173   }
174
175   /**
176    * Gets the app root.
177    *
178    * @return string
179    */
180   public static function root() {
181     return static::getContainer()->get('app.root');
182   }
183
184   /**
185    * Gets the active install profile.
186    *
187    * @return string|null
188    *   The name of the active install profile.
189    */
190   public static function installProfile() {
191     return static::getContainer()->getParameter('install_profile');
192   }
193
194   /**
195    * Indicates if there is a currently active request object.
196    *
197    * @return bool
198    *   TRUE if there is a currently active request object, FALSE otherwise.
199    */
200   public static function hasRequest() {
201     // Check hasContainer() first in order to always return a Boolean.
202     return static::hasContainer() && static::getContainer()->has('request_stack') && static::getContainer()->get('request_stack')->getCurrentRequest() !== NULL;
203   }
204
205   /**
206    * Retrieves the currently active request object.
207    *
208    * Note: The use of this wrapper in particular is especially discouraged. Most
209    * code should not need to access the request directly.  Doing so means it
210    * will only function when handling an HTTP request, and will require special
211    * modification or wrapping when run from a command line tool, from certain
212    * queue processors, or from automated tests.
213    *
214    * If code must access the request, it is considerably better to register
215    * an object with the Service Container and give it a setRequest() method
216    * that is configured to run when the service is created.  That way, the
217    * correct request object can always be provided by the container and the
218    * service can still be unit tested.
219    *
220    * If this method must be used, never save the request object that is
221    * returned.  Doing so may lead to inconsistencies as the request object is
222    * volatile and may change at various times, such as during a subrequest.
223    *
224    * @return \Symfony\Component\HttpFoundation\Request
225    *   The currently active request object.
226    */
227   public static function request() {
228     return static::getContainer()->get('request_stack')->getCurrentRequest();
229   }
230
231   /**
232    * Retrieves the request stack.
233    *
234    * @return \Symfony\Component\HttpFoundation\RequestStack
235    *   The request stack
236    */
237   public static function requestStack() {
238     return static::getContainer()->get('request_stack');
239   }
240
241   /**
242    * Retrieves the currently active route match object.
243    *
244    * @return \Drupal\Core\Routing\RouteMatchInterface
245    *   The currently active route match object.
246    */
247   public static function routeMatch() {
248     return static::getContainer()->get('current_route_match');
249   }
250
251   /**
252    * Gets the current active user.
253    *
254    * @return \Drupal\Core\Session\AccountProxyInterface
255    */
256   public static function currentUser() {
257     return static::getContainer()->get('current_user');
258   }
259
260   /**
261    * Retrieves the entity manager service.
262    *
263    * @return \Drupal\Core\Entity\EntityManagerInterface
264    *   The entity manager service.
265    *
266    * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
267    *   Use \Drupal::entityTypeManager() instead in most cases. If the needed
268    *   method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the
269    *   deprecated \Drupal\Core\Entity\EntityManager to find the
270    *   correct interface or service.
271    */
272   public static function entityManager() {
273     return static::getContainer()->get('entity.manager');
274   }
275
276   /**
277    * Retrieves the entity type manager.
278    *
279    * @return \Drupal\Core\Entity\EntityTypeManagerInterface
280    *   The entity type manager.
281    */
282   public static function entityTypeManager() {
283     return static::getContainer()->get('entity_type.manager');
284   }
285
286   /**
287    * Returns the current primary database.
288    *
289    * @return \Drupal\Core\Database\Connection
290    *   The current active database's master connection.
291    */
292   public static function database() {
293     return static::getContainer()->get('database');
294   }
295
296   /**
297    * Returns the requested cache bin.
298    *
299    * @param string $bin
300    *   (optional) The cache bin for which the cache object should be returned,
301    *   defaults to 'default'.
302    *
303    * @return \Drupal\Core\Cache\CacheBackendInterface
304    *   The cache object associated with the specified bin.
305    *
306    * @ingroup cache
307    */
308   public static function cache($bin = 'default') {
309     return static::getContainer()->get('cache.' . $bin);
310   }
311
312   /**
313    * Retrieves the class resolver.
314    *
315    * This is to be used in procedural code such as module files to instantiate
316    * an object of a class that implements
317    * \Drupal\Core\DependencyInjection\ContainerInjectionInterface.
318    *
319    * One common usecase is to provide a class which contains the actual code
320    * of a hook implementation, without having to create a service.
321    *
322    * @param string $class
323    *   (optional) A class name to instantiate.
324    *
325    * @return \Drupal\Core\DependencyInjection\ClassResolverInterface|object
326    *   The class resolver or if $class is provided, a class instance with a
327    *   given class definition.
328    *
329    * @throws \InvalidArgumentException
330    *   If $class does not exist.
331    */
332   public static function classResolver($class = NULL) {
333     if ($class) {
334       return static::getContainer()->get('class_resolver')->getInstanceFromDefinition($class);
335     }
336     return static::getContainer()->get('class_resolver');
337   }
338
339   /**
340    * Returns an expirable key value store collection.
341    *
342    * @param string $collection
343    *   The name of the collection holding key and value pairs.
344    *
345    * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
346    *   An expirable key value store collection.
347    */
348   public static function keyValueExpirable($collection) {
349     return static::getContainer()->get('keyvalue.expirable')->get($collection);
350   }
351
352   /**
353    * Returns the locking layer instance.
354    *
355    * @return \Drupal\Core\Lock\LockBackendInterface
356    *
357    * @ingroup lock
358    */
359   public static function lock() {
360     return static::getContainer()->get('lock');
361   }
362
363   /**
364    * Retrieves a configuration object.
365    *
366    * This is the main entry point to the configuration API. Calling
367    * @code \Drupal::config('book.admin') @endcode will return a configuration
368    * object in which the book module can store its administrative settings.
369    *
370    * @param string $name
371    *   The name of the configuration object to retrieve. The name corresponds to
372    *   a configuration file. For @code \Drupal::config('book.admin') @endcode, the config
373    *   object returned will contain the contents of book.admin configuration file.
374    *
375    * @return \Drupal\Core\Config\ImmutableConfig
376    *   An immutable configuration object.
377    */
378   public static function config($name) {
379     return static::getContainer()->get('config.factory')->get($name);
380   }
381
382   /**
383    * Retrieves the configuration factory.
384    *
385    * This is mostly used to change the override settings on the configuration
386    * factory. For example, changing the language, or turning all overrides on
387    * or off.
388    *
389    * @return \Drupal\Core\Config\ConfigFactoryInterface
390    *   The configuration factory service.
391    */
392   public static function configFactory() {
393     return static::getContainer()->get('config.factory');
394   }
395
396   /**
397    * Returns a queue for the given queue name.
398    *
399    * The following values can be set in your settings.php file's $settings
400    * array to define which services are used for queues:
401    * - queue_reliable_service_$name: The container service to use for the
402    *   reliable queue $name.
403    * - queue_service_$name: The container service to use for the
404    *   queue $name.
405    * - queue_default: The container service to use by default for queues
406    *   without overrides. This defaults to 'queue.database'.
407    *
408    * @param string $name
409    *   The name of the queue to work with.
410    * @param bool $reliable
411    *   (optional) TRUE if the ordering of items and guaranteeing every item
412    *   executes at least once is important, FALSE if scalability is the main
413    *   concern. Defaults to FALSE.
414    *
415    * @return \Drupal\Core\Queue\QueueInterface
416    *   The queue object for a given name.
417    */
418   public static function queue($name, $reliable = FALSE) {
419     return static::getContainer()->get('queue')->get($name, $reliable);
420   }
421
422   /**
423    * Returns a key/value storage collection.
424    *
425    * @param string $collection
426    *   Name of the key/value collection to return.
427    *
428    * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
429    */
430   public static function keyValue($collection) {
431     return static::getContainer()->get('keyvalue')->get($collection);
432   }
433
434   /**
435    * Returns the state storage service.
436    *
437    * Use this to store machine-generated data, local to a specific environment
438    * that does not need deploying and does not need human editing; for example,
439    * the last time cron was run. Data which needs to be edited by humans and
440    * needs to be the same across development, production, etc. environments
441    * (for example, the system maintenance message) should use \Drupal::config() instead.
442    *
443    * @return \Drupal\Core\State\StateInterface
444    */
445   public static function state() {
446     return static::getContainer()->get('state');
447   }
448
449   /**
450    * Returns the default http client.
451    *
452    * @return \GuzzleHttp\Client
453    *   A guzzle http client instance.
454    */
455   public static function httpClient() {
456     return static::getContainer()->get('http_client');
457   }
458
459   /**
460    * Returns the entity query object for this entity type.
461    *
462    * @param string $entity_type
463    *   The entity type (for example, node) for which the query object should be
464    *   returned.
465    * @param string $conjunction
466    *   (optional) Either 'AND' if all conditions in the query need to apply, or
467    *   'OR' if any of them is sufficient. Defaults to 'AND'.
468    *
469    * @return \Drupal\Core\Entity\Query\QueryInterface
470    *   The query object that can query the given entity type.
471    */
472   public static function entityQuery($entity_type, $conjunction = 'AND') {
473     return static::entityTypeManager()->getStorage($entity_type)->getQuery($conjunction);
474   }
475
476   /**
477    * Returns the entity query aggregate object for this entity type.
478    *
479    * @param string $entity_type
480    *   The entity type (for example, node) for which the query object should be
481    *   returned.
482    * @param string $conjunction
483    *   (optional) Either 'AND' if all conditions in the query need to apply, or
484    *   'OR' if any of them is sufficient. Defaults to 'AND'.
485    *
486    * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
487    *   The query object that can query the given entity type.
488    */
489   public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
490     return static::entityTypeManager()->getStorage($entity_type)->getAggregateQuery($conjunction);
491   }
492
493   /**
494    * Returns the flood instance.
495    *
496    * @return \Drupal\Core\Flood\FloodInterface
497    */
498   public static function flood() {
499     return static::getContainer()->get('flood');
500   }
501
502   /**
503    * Returns the module handler.
504    *
505    * @return \Drupal\Core\Extension\ModuleHandlerInterface
506    */
507   public static function moduleHandler() {
508     return static::getContainer()->get('module_handler');
509   }
510
511   /**
512    * Returns the typed data manager service.
513    *
514    * Use the typed data manager service for creating typed data objects.
515    *
516    * @return \Drupal\Core\TypedData\TypedDataManagerInterface
517    *   The typed data manager.
518    *
519    * @see \Drupal\Core\TypedData\TypedDataManager::create()
520    */
521   public static function typedDataManager() {
522     return static::getContainer()->get('typed_data_manager');
523   }
524
525   /**
526    * Returns the token service.
527    *
528    * @return \Drupal\Core\Utility\Token
529    *   The token service.
530    */
531   public static function token() {
532     return static::getContainer()->get('token');
533   }
534
535   /**
536    * Returns the url generator service.
537    *
538    * @return \Drupal\Core\Routing\UrlGeneratorInterface
539    *   The url generator service.
540    */
541   public static function urlGenerator() {
542     return static::getContainer()->get('url_generator');
543   }
544
545   /**
546    * Generates a URL string for a specific route based on the given parameters.
547    *
548    * This method is a convenience wrapper for generating URL strings for URLs
549    * that have Drupal routes (that is, most pages generated by Drupal) using
550    * the \Drupal\Core\Url object. See \Drupal\Core\Url::fromRoute() for
551    * detailed documentation. For non-routed local URIs relative to
552    * the base path (like robots.txt) use Url::fromUri()->toString() with the
553    * base: scheme.
554    *
555    * @param string $route_name
556    *   The name of the route.
557    * @param array $route_parameters
558    *   (optional) An associative array of parameter names and values.
559    * @param array $options
560    *   (optional) An associative array of additional options.
561    * @param bool $collect_bubbleable_metadata
562    *   (optional) Defaults to FALSE. When TRUE, both the generated URL and its
563    *   associated bubbleable metadata are returned.
564    *
565    * @return string|\Drupal\Core\GeneratedUrl
566    *   A string containing a URL to the given path.
567    *   When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is
568    *   returned, containing the generated URL plus bubbleable metadata.
569    *
570    * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
571    * @see \Drupal\Core\Url
572    * @see \Drupal\Core\Url::fromRoute()
573    * @see \Drupal\Core\Url::fromUri()
574    *
575    * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0.
576    *   Instead create a \Drupal\Core\Url object directly, for example using
577    *   Url::fromRoute().
578    */
579   public static function url($route_name, $route_parameters = [], $options = [], $collect_bubbleable_metadata = FALSE) {
580     return static::getContainer()->get('url_generator')->generateFromRoute($route_name, $route_parameters, $options, $collect_bubbleable_metadata);
581   }
582
583   /**
584    * Returns the link generator service.
585    *
586    * @return \Drupal\Core\Utility\LinkGeneratorInterface
587    */
588   public static function linkGenerator() {
589     return static::getContainer()->get('link_generator');
590   }
591
592   /**
593    * Renders a link with a given link text and Url object.
594    *
595    * This method is a convenience wrapper for the link generator service's
596    * generate() method.
597    *
598    * @param string $text
599    *   The link text for the anchor tag.
600    * @param \Drupal\Core\Url $url
601    *   The URL object used for the link.
602    *
603    * @return \Drupal\Core\GeneratedLink
604    *   A GeneratedLink object containing a link to the given route and
605    *   parameters and bubbleable metadata.
606    *
607    * @see \Drupal\Core\Utility\LinkGeneratorInterface::generate()
608    * @see \Drupal\Core\Url
609    *
610    * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
611    *   Use \Drupal\Core\Link instead.
612    *   Example:
613    *   @code
614    *     $link = Link::fromTextAndUrl($text, $url);
615    *   @endcode
616    */
617   public static function l($text, Url $url) {
618     return static::getContainer()->get('link_generator')->generate($text, $url);
619   }
620
621   /**
622    * Returns the string translation service.
623    *
624    * @return \Drupal\Core\StringTranslation\TranslationManager
625    *   The string translation manager.
626    */
627   public static function translation() {
628     return static::getContainer()->get('string_translation');
629   }
630
631   /**
632    * Returns the language manager service.
633    *
634    * @return \Drupal\Core\Language\LanguageManagerInterface
635    *   The language manager.
636    */
637   public static function languageManager() {
638     return static::getContainer()->get('language_manager');
639   }
640
641   /**
642    * Returns the CSRF token manager service.
643    *
644    * The generated token is based on the session ID of the current user. Normally,
645    * anonymous users do not have a session, so the generated token will be
646    * different on every page request. To generate a token for users without a
647    * session, manually start a session prior to calling this function.
648    *
649    * @return \Drupal\Core\Access\CsrfTokenGenerator
650    *   The CSRF token manager.
651    *
652    * @see \Drupal\Core\Session\SessionManager::start()
653    */
654   public static function csrfToken() {
655     return static::getContainer()->get('csrf_token');
656   }
657
658   /**
659    * Returns the transliteration service.
660    *
661    * @return \Drupal\Core\Transliteration\PhpTransliteration
662    *   The transliteration manager.
663    */
664   public static function transliteration() {
665     return static::getContainer()->get('transliteration');
666   }
667
668   /**
669    * Returns the form builder service.
670    *
671    * @return \Drupal\Core\Form\FormBuilderInterface
672    *   The form builder.
673    */
674   public static function formBuilder() {
675     return static::getContainer()->get('form_builder');
676   }
677
678   /**
679    * Gets the theme service.
680    *
681    * @return \Drupal\Core\Theme\ThemeManagerInterface
682    */
683   public static function theme() {
684     return static::getContainer()->get('theme.manager');
685   }
686
687   /**
688    * Gets the syncing state.
689    *
690    * @return bool
691    *   Returns TRUE is syncing flag set.
692    */
693   public static function isConfigSyncing() {
694     return static::getContainer()->get('config.installer')->isSyncing();
695   }
696
697   /**
698    * Returns a channel logger object.
699    *
700    * @param string $channel
701    *   The name of the channel. Can be any string, but the general practice is
702    *   to use the name of the subsystem calling this.
703    *
704    * @return \Psr\Log\LoggerInterface
705    *   The logger for this channel.
706    */
707   public static function logger($channel) {
708     return static::getContainer()->get('logger.factory')->get($channel);
709   }
710
711   /**
712    * Returns the menu tree.
713    *
714    * @return \Drupal\Core\Menu\MenuLinkTreeInterface
715    *   The menu tree.
716    */
717   public static function menuTree() {
718     return static::getContainer()->get('menu.link_tree');
719   }
720
721   /**
722    * Returns the path validator.
723    *
724    * @return \Drupal\Core\Path\PathValidatorInterface
725    */
726   public static function pathValidator() {
727     return static::getContainer()->get('path.validator');
728   }
729
730   /**
731    * Returns the access manager service.
732    *
733    * @return \Drupal\Core\Access\AccessManagerInterface
734    *   The access manager service.
735    */
736   public static function accessManager() {
737     return static::getContainer()->get('access_manager');
738   }
739
740   /**
741    * Returns the redirect destination helper.
742    *
743    * @return \Drupal\Core\Routing\RedirectDestinationInterface
744    *   The redirect destination helper.
745    */
746   public static function destination() {
747     return static::getContainer()->get('redirect.destination');
748   }
749
750   /**
751    * Returns the entity definition update manager.
752    *
753    * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
754    *   The entity definition update manager.
755    */
756   public static function entityDefinitionUpdateManager() {
757     return static::getContainer()->get('entity.definition_update_manager');
758   }
759
760   /**
761    * Returns the time service.
762    *
763    * @return \Drupal\Component\Datetime\TimeInterface
764    *   The time service.
765    */
766   public static function time() {
767     return static::getContainer()->get('datetime.time');
768   }
769
770   /**
771    * Returns the messenger.
772    *
773    * @return \Drupal\Core\Messenger\MessengerInterface
774    *   The messenger.
775    */
776   public static function messenger() {
777     // @todo Replace with service once LegacyMessenger is removed in 9.0.0.
778     // @see https://www.drupal.org/node/2928994
779     return new LegacyMessenger();
780   }
781
782 }