comparison core/lib/Drupal.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 7a779792577d
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 /**
4 * @file
5 * Contains \Drupal.
6 */
7
8 use Drupal\Core\DependencyInjection\ContainerNotInitializedException;
9 use Symfony\Component\DependencyInjection\ContainerInterface;
10 use Drupal\Core\Url;
11
12 /**
13 * Static Service Container wrapper.
14 *
15 * Generally, code in Drupal should accept its dependencies via either
16 * constructor injection or setter method injection. However, there are cases,
17 * particularly in legacy procedural code, where that is infeasible. This
18 * class acts as a unified global accessor to arbitrary services within the
19 * system in order to ease the transition from procedural code to injected OO
20 * code.
21 *
22 * The container is built by the kernel and passed in to this class which stores
23 * it statically. The container always contains the services from
24 * \Drupal\Core\CoreServiceProvider, the service providers of enabled modules and any other
25 * service providers defined in $GLOBALS['conf']['container_service_providers'].
26 *
27 * This class exists only to support legacy code that cannot be dependency
28 * injected. If your code needs it, consider refactoring it to be object
29 * oriented, if possible. When this is not possible, for instance in the case of
30 * hook implementations, and your code is more than a few non-reusable lines, it
31 * is recommended to instantiate an object implementing the actual logic.
32 *
33 * @code
34 * // Legacy procedural code.
35 * function hook_do_stuff() {
36 * $lock = lock()->acquire('stuff_lock');
37 * // ...
38 * }
39 *
40 * // Correct procedural code.
41 * function hook_do_stuff() {
42 * $lock = \Drupal::lock()->acquire('stuff_lock');
43 * // ...
44 * }
45 *
46 * // The preferred way: dependency injected code.
47 * function hook_do_stuff() {
48 * // Move the actual implementation to a class and instantiate it.
49 * $instance = new StuffDoingClass(\Drupal::lock());
50 * $instance->doStuff();
51 *
52 * // Or, even better, rely on the service container to avoid hard coding a
53 * // specific interface implementation, so that the actual logic can be
54 * // swapped. This might not always make sense, but in general it is a good
55 * // practice.
56 * \Drupal::service('stuff.doing')->doStuff();
57 * }
58 *
59 * interface StuffDoingInterface {
60 * public function doStuff();
61 * }
62 *
63 * class StuffDoingClass implements StuffDoingInterface {
64 * protected $lockBackend;
65 *
66 * public function __construct(LockBackendInterface $lock_backend) {
67 * $this->lockBackend = $lock_backend;
68 * }
69 *
70 * public function doStuff() {
71 * $lock = $this->lockBackend->acquire('stuff_lock');
72 * // ...
73 * }
74 * }
75 * @endcode
76 *
77 * @see \Drupal\Core\DrupalKernel
78 */
79 class Drupal {
80
81 /**
82 * The current system version.
83 */
84 const VERSION = '8.4.2';
85
86 /**
87 * Core API compatibility.
88 */
89 const CORE_COMPATIBILITY = '8.x';
90
91 /**
92 * Core minimum schema version.
93 */
94 const CORE_MINIMUM_SCHEMA_VERSION = 8000;
95
96 /**
97 * The currently active container object, or NULL if not initialized yet.
98 *
99 * @var \Symfony\Component\DependencyInjection\ContainerInterface|null
100 */
101 protected static $container;
102
103 /**
104 * Sets a new global container.
105 *
106 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
107 * A new container instance to replace the current.
108 */
109 public static function setContainer(ContainerInterface $container) {
110 static::$container = $container;
111 }
112
113 /**
114 * Unsets the global container.
115 */
116 public static function unsetContainer() {
117 static::$container = NULL;
118 }
119
120 /**
121 * Returns the currently active global container.
122 *
123 * @return \Symfony\Component\DependencyInjection\ContainerInterface|null
124 *
125 * @throws \Drupal\Core\DependencyInjection\ContainerNotInitializedException
126 */
127 public static function getContainer() {
128 if (static::$container === NULL) {
129 throw new ContainerNotInitializedException('\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.');
130 }
131 return static::$container;
132 }
133
134 /**
135 * Returns TRUE if the container has been initialized, FALSE otherwise.
136 *
137 * @return bool
138 */
139 public static function hasContainer() {
140 return static::$container !== NULL;
141 }
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 * Retrives 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 * @return \Drupal\Core\DependencyInjection\ClassResolverInterface
323 * The class resolver.
324 */
325 public static function classResolver() {
326 return static::getContainer()->get('class_resolver');
327 }
328
329 /**
330 * Returns an expirable key value store collection.
331 *
332 * @param string $collection
333 * The name of the collection holding key and value pairs.
334 *
335 * @return \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
336 * An expirable key value store collection.
337 */
338 public static function keyValueExpirable($collection) {
339 return static::getContainer()->get('keyvalue.expirable')->get($collection);
340 }
341
342 /**
343 * Returns the locking layer instance.
344 *
345 * @return \Drupal\Core\Lock\LockBackendInterface
346 *
347 * @ingroup lock
348 */
349 public static function lock() {
350 return static::getContainer()->get('lock');
351 }
352
353 /**
354 * Retrieves a configuration object.
355 *
356 * This is the main entry point to the configuration API. Calling
357 * @code \Drupal::config('book.admin') @endcode will return a configuration
358 * object in which the book module can store its administrative settings.
359 *
360 * @param string $name
361 * The name of the configuration object to retrieve. The name corresponds to
362 * a configuration file. For @code \Drupal::config('book.admin') @endcode, the config
363 * object returned will contain the contents of book.admin configuration file.
364 *
365 * @return \Drupal\Core\Config\ImmutableConfig
366 * An immutable configuration object.
367 */
368 public static function config($name) {
369 return static::getContainer()->get('config.factory')->get($name);
370 }
371
372 /**
373 * Retrieves the configuration factory.
374 *
375 * This is mostly used to change the override settings on the configuration
376 * factory. For example, changing the language, or turning all overrides on
377 * or off.
378 *
379 * @return \Drupal\Core\Config\ConfigFactoryInterface
380 * The configuration factory service.
381 */
382 public static function configFactory() {
383 return static::getContainer()->get('config.factory');
384 }
385
386 /**
387 * Returns a queue for the given queue name.
388 *
389 * The following values can be set in your settings.php file's $settings
390 * array to define which services are used for queues:
391 * - queue_reliable_service_$name: The container service to use for the
392 * reliable queue $name.
393 * - queue_service_$name: The container service to use for the
394 * queue $name.
395 * - queue_default: The container service to use by default for queues
396 * without overrides. This defaults to 'queue.database'.
397 *
398 * @param string $name
399 * The name of the queue to work with.
400 * @param bool $reliable
401 * (optional) TRUE if the ordering of items and guaranteeing every item
402 * executes at least once is important, FALSE if scalability is the main
403 * concern. Defaults to FALSE.
404 *
405 * @return \Drupal\Core\Queue\QueueInterface
406 * The queue object for a given name.
407 */
408 public static function queue($name, $reliable = FALSE) {
409 return static::getContainer()->get('queue')->get($name, $reliable);
410 }
411
412 /**
413 * Returns a key/value storage collection.
414 *
415 * @param string $collection
416 * Name of the key/value collection to return.
417 *
418 * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
419 */
420 public static function keyValue($collection) {
421 return static::getContainer()->get('keyvalue')->get($collection);
422 }
423
424 /**
425 * Returns the state storage service.
426 *
427 * Use this to store machine-generated data, local to a specific environment
428 * that does not need deploying and does not need human editing; for example,
429 * the last time cron was run. Data which needs to be edited by humans and
430 * needs to be the same across development, production, etc. environments
431 * (for example, the system maintenance message) should use \Drupal::config() instead.
432 *
433 * @return \Drupal\Core\State\StateInterface
434 */
435 public static function state() {
436 return static::getContainer()->get('state');
437 }
438
439 /**
440 * Returns the default http client.
441 *
442 * @return \GuzzleHttp\Client
443 * A guzzle http client instance.
444 */
445 public static function httpClient() {
446 return static::getContainer()->get('http_client');
447 }
448
449 /**
450 * Returns the entity query object for this entity type.
451 *
452 * @param string $entity_type
453 * The entity type (for example, node) for which the query object should be
454 * returned.
455 * @param string $conjunction
456 * (optional) Either 'AND' if all conditions in the query need to apply, or
457 * 'OR' if any of them is sufficient. Defaults to 'AND'.
458 *
459 * @return \Drupal\Core\Entity\Query\QueryInterface
460 * The query object that can query the given entity type.
461 */
462 public static function entityQuery($entity_type, $conjunction = 'AND') {
463 return static::entityTypeManager()->getStorage($entity_type)->getQuery($conjunction);
464 }
465
466 /**
467 * Returns the entity query aggregate object for this entity type.
468 *
469 * @param string $entity_type
470 * The entity type (for example, node) for which the query object should be
471 * returned.
472 * @param string $conjunction
473 * (optional) Either 'AND' if all conditions in the query need to apply, or
474 * 'OR' if any of them is sufficient. Defaults to 'AND'.
475 *
476 * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
477 * The query object that can query the given entity type.
478 */
479 public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
480 return static::entityTypeManager()->getStorage($entity_type)->getAggregateQuery($conjunction);
481 }
482
483 /**
484 * Returns the flood instance.
485 *
486 * @return \Drupal\Core\Flood\FloodInterface
487 */
488 public static function flood() {
489 return static::getContainer()->get('flood');
490 }
491
492 /**
493 * Returns the module handler.
494 *
495 * @return \Drupal\Core\Extension\ModuleHandlerInterface
496 */
497 public static function moduleHandler() {
498 return static::getContainer()->get('module_handler');
499 }
500
501 /**
502 * Returns the typed data manager service.
503 *
504 * Use the typed data manager service for creating typed data objects.
505 *
506 * @return \Drupal\Core\TypedData\TypedDataManagerInterface
507 * The typed data manager.
508 *
509 * @see \Drupal\Core\TypedData\TypedDataManager::create()
510 */
511 public static function typedDataManager() {
512 return static::getContainer()->get('typed_data_manager');
513 }
514
515 /**
516 * Returns the token service.
517 *
518 * @return \Drupal\Core\Utility\Token
519 * The token service.
520 */
521 public static function token() {
522 return static::getContainer()->get('token');
523 }
524
525 /**
526 * Returns the url generator service.
527 *
528 * @return \Drupal\Core\Routing\UrlGeneratorInterface
529 * The url generator service.
530 */
531 public static function urlGenerator() {
532 return static::getContainer()->get('url_generator');
533 }
534
535 /**
536 * Generates a URL string for a specific route based on the given parameters.
537 *
538 * This method is a convenience wrapper for generating URL strings for URLs
539 * that have Drupal routes (that is, most pages generated by Drupal) using
540 * the \Drupal\Core\Url object. See \Drupal\Core\Url::fromRoute() for
541 * detailed documentation. For non-routed local URIs relative to
542 * the base path (like robots.txt) use Url::fromUri()->toString() with the
543 * base: scheme.
544 *
545 * @param string $route_name
546 * The name of the route.
547 * @param array $route_parameters
548 * (optional) An associative array of parameter names and values.
549 * @param array $options
550 * (optional) An associative array of additional options.
551 * @param bool $collect_bubbleable_metadata
552 * (optional) Defaults to FALSE. When TRUE, both the generated URL and its
553 * associated bubbleable metadata are returned.
554 *
555 * @return string|\Drupal\Core\GeneratedUrl
556 * A string containing a URL to the given path.
557 * When $collect_bubbleable_metadata is TRUE, a GeneratedUrl object is
558 * returned, containing the generated URL plus bubbleable metadata.
559 *
560 * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
561 * @see \Drupal\Core\Url
562 * @see \Drupal\Core\Url::fromRoute()
563 * @see \Drupal\Core\Url::fromUri()
564 *
565 * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0.
566 * Instead create a \Drupal\Core\Url object directly, for example using
567 * Url::fromRoute().
568 */
569 public static function url($route_name, $route_parameters = [], $options = [], $collect_bubbleable_metadata = FALSE) {
570 return static::getContainer()->get('url_generator')->generateFromRoute($route_name, $route_parameters, $options, $collect_bubbleable_metadata);
571 }
572
573 /**
574 * Returns the link generator service.
575 *
576 * @return \Drupal\Core\Utility\LinkGeneratorInterface
577 */
578 public static function linkGenerator() {
579 return static::getContainer()->get('link_generator');
580 }
581
582 /**
583 * Renders a link with a given link text and Url object.
584 *
585 * This method is a convenience wrapper for the link generator service's
586 * generate() method.
587 *
588 * @param string $text
589 * The link text for the anchor tag.
590 * @param \Drupal\Core\Url $url
591 * The URL object used for the link.
592 *
593 * @return \Drupal\Core\GeneratedLink
594 * A GeneratedLink object containing a link to the given route and
595 * parameters and bubbleable metadata.
596 *
597 * @see \Drupal\Core\Utility\LinkGeneratorInterface::generate()
598 * @see \Drupal\Core\Url
599 *
600 * @deprecated in Drupal 8.0.0 and will be removed before Drupal 9.0.0.
601 * Use \Drupal\Core\Link instead.
602 * Example:
603 * @code
604 * $link = Link::fromTextAndUrl($text, $url);
605 * @endcode
606 */
607 public static function l($text, Url $url) {
608 return static::getContainer()->get('link_generator')->generate($text, $url);
609 }
610
611 /**
612 * Returns the string translation service.
613 *
614 * @return \Drupal\Core\StringTranslation\TranslationManager
615 * The string translation manager.
616 */
617 public static function translation() {
618 return static::getContainer()->get('string_translation');
619 }
620
621 /**
622 * Returns the language manager service.
623 *
624 * @return \Drupal\Core\Language\LanguageManagerInterface
625 * The language manager.
626 */
627 public static function languageManager() {
628 return static::getContainer()->get('language_manager');
629 }
630
631 /**
632 * Returns the CSRF token manager service.
633 *
634 * The generated token is based on the session ID of the current user. Normally,
635 * anonymous users do not have a session, so the generated token will be
636 * different on every page request. To generate a token for users without a
637 * session, manually start a session prior to calling this function.
638 *
639 * @return \Drupal\Core\Access\CsrfTokenGenerator
640 * The CSRF token manager.
641 *
642 * @see \Drupal\Core\Session\SessionManager::start()
643 */
644 public static function csrfToken() {
645 return static::getContainer()->get('csrf_token');
646 }
647
648 /**
649 * Returns the transliteration service.
650 *
651 * @return \Drupal\Core\Transliteration\PhpTransliteration
652 * The transliteration manager.
653 */
654 public static function transliteration() {
655 return static::getContainer()->get('transliteration');
656 }
657
658 /**
659 * Returns the form builder service.
660 *
661 * @return \Drupal\Core\Form\FormBuilderInterface
662 * The form builder.
663 */
664 public static function formBuilder() {
665 return static::getContainer()->get('form_builder');
666 }
667
668 /**
669 * Gets the theme service.
670 *
671 * @return \Drupal\Core\Theme\ThemeManagerInterface
672 */
673 public static function theme() {
674 return static::getContainer()->get('theme.manager');
675 }
676
677 /**
678 * Gets the syncing state.
679 *
680 * @return bool
681 * Returns TRUE is syncing flag set.
682 */
683 public static function isConfigSyncing() {
684 return static::getContainer()->get('config.installer')->isSyncing();
685 }
686
687 /**
688 * Returns a channel logger object.
689 *
690 * @param string $channel
691 * The name of the channel. Can be any string, but the general practice is
692 * to use the name of the subsystem calling this.
693 *
694 * @return \Psr\Log\LoggerInterface
695 * The logger for this channel.
696 */
697 public static function logger($channel) {
698 return static::getContainer()->get('logger.factory')->get($channel);
699 }
700
701 /**
702 * Returns the menu tree.
703 *
704 * @return \Drupal\Core\Menu\MenuLinkTreeInterface
705 * The menu tree.
706 */
707 public static function menuTree() {
708 return static::getContainer()->get('menu.link_tree');
709 }
710
711 /**
712 * Returns the path validator.
713 *
714 * @return \Drupal\Core\Path\PathValidatorInterface
715 */
716 public static function pathValidator() {
717 return static::getContainer()->get('path.validator');
718 }
719
720 /**
721 * Returns the access manager service.
722 *
723 * @return \Drupal\Core\Access\AccessManagerInterface
724 * The access manager service.
725 */
726 public static function accessManager() {
727 return static::getContainer()->get('access_manager');
728 }
729
730 /**
731 * Returns the redirect destination helper.
732 *
733 * @return \Drupal\Core\Routing\RedirectDestinationInterface
734 * The redirect destination helper.
735 */
736 public static function destination() {
737 return static::getContainer()->get('redirect.destination');
738 }
739
740 /**
741 * Returns the entity definition update manager.
742 *
743 * @return \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
744 * The entity definition update manager.
745 */
746 public static function entityDefinitionUpdateManager() {
747 return static::getContainer()->get('entity.definition_update_manager');
748 }
749
750 /**
751 * Returns the time service.
752 *
753 * @return \Drupal\Component\Datetime\TimeInterface
754 * The time service.
755 */
756 public static function time() {
757 return static::getContainer()->get('datetime.time');
758 }
759
760 }