Drupal.php 22.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
<?php

/**
 * @file
 * Contains Drupal.
 */

use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * 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
22 23
 * \Drupal\Core\CoreServiceProvider, the service providers of enabled modules and any other
 * service providers defined in $GLOBALS['conf']['container_service_providers'].
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
 *
 * 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() {
40
 *     $lock = \Drupal::lock()->acquire('stuff_lock');
41 42 43 44 45 46
 *     // ...
 *   }
 *
 *   // The preferred way: dependency injected code.
 *   function hook_do_stuff() {
 *     // Move the actual implementation to a class and instantiate it.
47
 *     $instance = new StuffDoingClass(\Drupal::lock());
48 49 50 51 52 53
 *     $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.
54
 *     \Drupal::service('stuff.doing')->doStuff();
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
 *   }
 *
 *   interface StuffDoingInterface {
 *     public function doStuff();
 *   }
 *
 *   class StuffDoingClass implements StuffDoingInterface {
 *     protected $lockBackend;
 *
 *     public function __construct(LockBackendInterface $lockBackend) {
 *       $this->lockBackend = $lockBackend;
 *     }
 *
 *     public function doStuff() {
 *       $lock = $this->lockBackend->acquire('stuff_lock');
 *       // ...
 *     }
 *   }
 * @endcode
 *
 * @see \Drupal\Core\DrupalKernel
 */
class Drupal {

79 80 81 82 83 84 85 86 87 88
  /**
   * The current system version.
   */
  const VERSION = '8.0-dev';

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

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

94 95 96 97 98 99 100 101 102 103 104
  /**
   * The currently active container object.
   *
   * @var \Symfony\Component\DependencyInjection\ContainerInterface
   */
  protected static $container;

  /**
   * Sets a new global container.
   *
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
105 106 107
   *   A new container instance to replace the current. NULL may be passed by
   *   testing frameworks to ensure that the global state of a previous
   *   environment does not leak into a test.
108
   */
109
  public static function setContainer(ContainerInterface $container = NULL) {
110 111 112 113 114 115
    static::$container = $container;
  }

  /**
   * Returns the currently active global container.
   *
116 117
   * @deprecated This method is only useful for the testing environment. It
   * should not be used otherwise.
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
   *
   * @return \Symfony\Component\DependencyInjection\ContainerInterface
   */
  public static function getContainer() {
    return static::$container;
  }

  /**
   * 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.
   * @return mixed
   *   The specified service.
   */
  public static function service($id) {
    return static::$container->get($id);
  }

141 142 143 144 145 146 147 148 149 150 151 152 153
  /**
   * 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) {
    return static::$container && static::$container->has($id);
  }

154 155 156 157 158 159 160
  /**
   * 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() {
161
    return static::$container && static::$container->has('request_stack') && static::$container->get('request_stack')->getCurrentRequest() !== NULL;
162 163
  }

164 165 166
  /**
   * Retrieves the currently active request object.
   *
167
   * Note: The use of this wrapper in particular is especially discouraged. Most
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
   * 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() {
187
    return static::$container->get('request_stack')->getCurrentRequest();
188 189
  }

190 191 192 193 194 195 196 197 198 199
  /**
   * Retrieves the currently active route match object.
   *
   * @return \Drupal\Core\Routing\RouteMatchInterface
   *   The currently active route match object.
   */
  public static function routeMatch() {
    return static::$container->get('current_route_match');
  }

200 201 202
  /**
   * Gets the current active user.
   *
203
   * @return \Drupal\Core\Session\AccountProxyInterface
204 205 206 207 208
   */
  public static function currentUser() {
    return static::$container->get('current_user');
  }

209 210 211
  /**
   * Retrieves the entity manager service.
   *
212
   * @return \Drupal\Core\Entity\EntityManagerInterface
213 214 215
   *   The entity manager service.
   */
  public static function entityManager() {
216
    return static::$container->get('entity.manager');
217 218
  }

219 220 221 222 223 224 225 226 227 228
  /**
   * Returns the current primary database.
   *
   * @return \Drupal\Core\Database\Connection
   *   The current active database's master connection.
   */
  public static function database() {
    return static::$container->get('database');
  }

229 230 231 232 233
  /**
   * Returns the requested cache bin.
   *
   * @param string $bin
   *   (optional) The cache bin for which the cache object should be returned,
234
   *   defaults to 'default'.
235
   *
236
   * @return \Drupal\Core\Cache\CacheBackendInterface
237
   *   The cache object associated with the specified bin.
238 239
   *
   * @ingroup cache
240
   */
241
  public static function cache($bin = 'default') {
242 243 244
    return static::$container->get('cache.' . $bin);
  }

245 246 247 248 249 250 251 252 253 254 255 256 257
  /**
   * 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) {
    return static::$container->get('keyvalue.expirable')->get($collection);
  }

258 259 260 261
  /**
   * Returns the locking layer instance.
   *
   * @return \Drupal\Core\Lock\LockBackendInterface
262 263
   *
   * @ingroup lock
264 265 266 267 268
   */
  public static function lock() {
    return static::$container->get('lock');
  }

269 270 271 272
  /**
   * Retrieves a configuration object.
   *
   * This is the main entry point to the configuration API. Calling
273
   * @code \Drupal::config('book.admin') @endcode will return a configuration
274 275 276 277
   * object in which the book module can store its administrative settings.
   *
   * @param string $name
   *   The name of the configuration object to retrieve. The name corresponds to
278
   *   a configuration file. For @code \Drupal::config('book.admin') @endcode, the config
279 280 281 282 283 284 285 286 287
   *   object returned will contain the contents of book.admin configuration file.
   *
   * @return \Drupal\Core\Config\Config
   *   A configuration object.
   */
  public static function config($name) {
    return static::$container->get('config.factory')->get($name);
  }

288 289 290 291 292 293 294
  /**
   * 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.
   *
295
   * @return \Drupal\Core\Config\ConfigFactoryInterface
296
   *   The configuration factory service.
297 298 299 300 301
   */
  public static function configFactory() {
    return static::$container->get('config.factory');
  }

302 303 304
  /**
   * Returns a queue for the given queue name.
   *
305 306 307 308 309 310 311 312
   * 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'.
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
   *
   * @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) {
    return static::$container->get('queue')->get($name, $reliable);
  }

  /**
   * Returns a key/value storage collection.
   *
331
   * @param string $collection
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
   *   Name of the key/value collection to return.
   *
   * @return \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  public static function keyValue($collection) {
    return static::$container->get('keyvalue')->get($collection);
  }

  /**
   * 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
347
   * (for example, the system maintenance message) should use \Drupal::config() instead.
348
   *
349
   * @return \Drupal\Core\State\StateInterface
350 351 352 353 354 355 356 357
   */
  public static function state() {
    return static::$container->get('state');
  }

  /**
   * Returns the default http client.
   *
358
   * @return \GuzzleHttp\ClientInterface
359 360 361
   *   A guzzle http client instance.
   */
  public static function httpClient() {
362
    return static::$container->get('http_client');
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
  }

  /**
   * Returns the entity query object for this entity type.
   *
   * @param string $entity_type
   *   The entity type, e.g. node, for which the query object should be
   *   returned.
   * @param string $conjunction
   *   AND if all conditions in the query need to apply, OR if any of them is
   *   enough. Optional, defaults to AND.
   *
   * @return \Drupal\Core\Entity\Query\QueryInterface
   *   The query object that can query the given entity type.
   */
  public static function entityQuery($entity_type, $conjunction = 'AND') {
    return static::$container->get('entity.query')->get($entity_type, $conjunction);
  }

382 383 384
  /**
   * Returns the entity query aggregate object for this entity type.
   *
385
   * @param string $entity_type
386 387
   *   The entity type, e.g. node, for which the query object should be
   *   returned.
388
   * @param string $conjunction
389 390 391
   *   AND if all conditions in the query need to apply, OR if any of them is
   *   enough. Optional, defaults to AND.
   *
392
   * @return \Drupal\Core\Entity\Query\QueryAggregateInterface
393 394 395 396 397 398
   *   The query object that can query the given entity type.
   */
  public static function entityQueryAggregate($entity_type, $conjunction = 'AND') {
    return static::$container->get('entity.query')->getAggregate($entity_type, $conjunction);
  }

399 400 401 402 403 404 405 406 407 408 409 410
  /**
   * Returns the flood instance.
   *
   * @return \Drupal\Core\Flood\FloodInterface
   */
  public static function flood() {
    return static::$container->get('flood');
  }

  /**
   * Returns the module handler.
   *
411
   * @return \Drupal\Core\Extension\ModuleHandlerInterface
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
   */
  public static function moduleHandler() {
    return static::$container->get('module_handler');
  }

  /**
   * Returns the typed data manager service.
   *
   * Use the typed data manager service for creating typed data objects.
   *
   * @return \Drupal\Core\TypedData\TypedDataManager
   *   The typed data manager.
   *
   * @see \Drupal\Core\TypedData\TypedDataManager::create()
   */
427 428
  public static function typedDataManager() {
    return static::$container->get('typed_data_manager');
429 430
  }

431 432 433 434 435 436 437 438 439 440
  /**
   * Returns the token service.
   *
   * @return \Drupal\Core\Utility\Token
   *   The token service.
   */
  public static function token() {
    return static::$container->get('token');
  }

441 442 443
  /**
   * Returns the url generator service.
   *
444
   * @return \Drupal\Core\Routing\UrlGeneratorInterface
445 446 447 448
   *   The url generator service.
   */
  public static function urlGenerator() {
    return static::$container->get('url_generator');
449 450
  }

451 452 453 454 455 456 457
  /**
   * Generates a URL or path for a specific route based on the given parameters.
   *
   * Parameters that reference placeholders in the route pattern will be
   * substituted for them in the pattern. Extra params are added as query
   * strings to the URL.
   *
458
   * @param string $route_name
459
   *   The name of the route
460
   * @param array $route_parameters
461 462 463 464 465 466 467 468 469 470 471 472 473
   *   An associative array of parameter names and values.
   * @param array $options
   *   (optional) An associative array of additional options, with the following
   *   elements:
   *   - 'query': An array of query key/value-pairs (without any URL-encoding)
   *     to append to the URL. Merged with the parameters array.
   *   - 'fragment': A fragment identifier (named anchor) to append to the URL.
   *     Do not include the leading '#' character.
   *   - 'absolute': Defaults to FALSE. Whether to force the output to be an
   *     absolute link (beginning with http:). Useful for links that will be
   *     displayed outside the site, such as in an RSS feed.
   *   - 'language': An optional language object used to look up the alias
   *     for the URL. If $options['language'] is omitted, the language will be
474 475
   *     obtained from
   *     \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL).
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
   *   - 'https': Whether this URL should point to a secure location. If not
   *     defined, the current scheme is used, so the user stays on HTTP or HTTPS
   *     respectively. if mixed mode sessions are permitted, TRUE enforces HTTPS
   *     and FALSE enforces HTTP.
   *
   * @return string
   *   The generated URL for the given route.
   *
   * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
   *   Thrown when the named route doesn't exist.
   * @throws \Symfony\Component\Routing\Exception\MissingMandatoryParametersException
   *   Thrown when some parameters are missing that are mandatory for the route.
   * @throws \Symfony\Component\Routing\Exception\InvalidParameterException
   *   Thrown when a parameter value for a placeholder is not correct because it
   *   does not match the requirement.
   *
   * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
   */
494
  public static function url($route_name, $route_parameters = array(), $options = array()) {
495 496 497
    return static::$container->get('url_generator')->generateFromRoute($route_name, $route_parameters, $options);
  }

498 499 500 501 502 503 504
  /**
   * Returns the link generator service.
   *
   * @return \Drupal\Core\Utility\LinkGeneratorInterface
   */
  public static function linkGenerator() {
    return static::$container->get('link_generator');
505 506 507 508 509 510 511 512 513 514 515 516
  }

  /**
   * Renders a link to a route given a route name and its parameters.
   *
   * This function correctly handles aliased paths and sanitizing text, so all
   * internal links output by modules should be generated by this function if
   * possible.
   *
   * However, for links enclosed in translatable text you should use t() and
   * embed the HTML anchor tag directly in the translated string. For example:
   * @code
517
   * t('Visit the <a href="@url">content types</a> page', array('@url' => \Drupal::url('node.overview_types')));
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
   * @endcode
   * This keeps the context of the link title ('settings' in the example) for
   * translators.
   *
   * @param string|array $text
   *   The link text for the anchor tag as a translated string or render array.
   * @param string $route_name
   *   The name of the route to use to generate the link.
   * @param array $parameters
   *   (optional) Any parameters needed to render the route path pattern.
   * @param array $options
   *   (optional) An associative array of additional options. Defaults to an
   *   empty array. It may contain the following elements:
   *   - 'query': An array of query key/value-pairs (without any URL-encoding) to
   *     append to the URL.
   *   - absolute: Whether to force the output to be an absolute link (beginning
   *     with http:). Useful for links that will be displayed outside the site,
   *     such as in an RSS feed. Defaults to FALSE.
   *   - attributes: An associative array of HTML attributes to apply to the
   *     anchor tag. If element 'class' is included, it must be an array; 'title'
   *     must be a string; other elements are more flexible, as they just need
   *     to work as an argument for the constructor of the class
   *     Drupal\Core\Template\Attribute($options['attributes']).
   *   - html: Whether $text is HTML or just plain-text. For
   *     example, to make an image tag into a link, this must be set to TRUE, or
   *     you will see the escaped HTML image tag. $text is not sanitized if
   *     'html' is TRUE. The calling function must ensure that $text is already
   *     safe. Defaults to FALSE.
   *   - language: An optional language object. If the path being linked to is
   *     internal to the site, $options['language'] is used to determine whether
   *     the link is "active", or pointing to the current page (the language as
   *     well as the path must match).
   *
   * @return string
   *   An HTML string containing a link to the given route and parameters.
   *
   * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
   *   Thrown when the named route doesn't exist.
   * @throws \Symfony\Component\Routing\Exception\MissingMandatoryParametersException
   *   Thrown when some parameters are missing that are mandatory for the route.
   * @throws \Symfony\Component\Routing\Exception\InvalidParameterException
   *   Thrown when a parameter value for a placeholder is not correct because it
   *   does not match the requirement.
   *
   * @see \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()
   * @see \Drupal\Core\Utility\LinkGeneratorInterface::generate()
   */
565
  public static function l($text, $route_name, array $parameters = array(), array $options = array()) {
566
    return static::$container->get('link_generator')->generate($text, $route_name, $parameters, $options);
567 568
  }

569 570 571
  /**
   * Returns the string translation service.
   *
572
   * @return \Drupal\Core\StringTranslation\TranslationManager
573 574 575 576 577 578
   *   The string translation manager.
   */
  public static function translation() {
    return static::$container->get('string_translation');
  }

579 580 581
  /**
   * Returns the language manager service.
   *
582
   * @return \Drupal\Core\Language\LanguageManagerInterface
583 584 585 586 587 588
   *   The language manager.
   */
  public static function languageManager() {
    return static::$container->get('language_manager');
  }

589 590 591
  /**
   * Returns the CSRF token manager service.
   *
592 593 594 595 596
   * 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.
   *
597 598
   * @return \Drupal\Core\Access\CsrfTokenGenerator
   *   The CSRF token manager.
599
   *
600
   * @see \Drupal\Core\Session\SessionManager::start()
601 602 603 604 605
   */
  public static function csrfToken() {
    return static::$container->get('csrf_token');
  }

606 607 608 609 610 611 612 613 614 615
  /**
   * Returns the transliteration service.
   *
   * @return \Drupal\Core\Transliteration\PHPTransliteration
   *   The transliteration manager.
   */
  public static function transliteration() {
    return static::$container->get('transliteration');
  }

616 617 618 619 620 621 622 623 624 625
  /**
   * Returns the form builder service.
   *
   * @return \Drupal\Core\Form\FormBuilderInterface
   *   The form builder.
   */
  public static function formBuilder() {
    return static::$container->get('form_builder');
  }

626 627 628 629 630 631
  /**
   * Gets the syncing state.
   *
   * @return bool
   *   Returns TRUE is syncing flag set.
   */
632
  public static function isConfigSyncing() {
633 634 635
    return static::$container->get('config.installer')->isSyncing();
  }

636 637 638 639 640 641 642 643 644 645 646 647 648 649
  /**
   * 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.
   *
   * @return \Drupal\Core\Logger\LoggerChannelInterface
   *   The logger for this channel.
   */
  public static function logger($channel) {
    return static::$container->get('logger.factory')->get($channel);
  }

650 651 652 653 654 655 656 657 658 659
  /**
   * Returns the menu tree.
   *
   * @return \Drupal\Core\Menu\MenuLinkTreeInterface
   *   The menu tree.
   */
  public static function menuTree() {
    return static::$container->get('menu.link_tree');
  }

660
}