3 namespace Drupal\Component\DependencyInjection;
5 use Symfony\Component\DependencyInjection\ContainerInterface;
6 use Symfony\Component\DependencyInjection\IntrospectableContainerInterface;
7 use Symfony\Component\DependencyInjection\ResettableContainerInterface;
8 use Symfony\Component\DependencyInjection\ScopeInterface;
9 use Symfony\Component\DependencyInjection\Exception\LogicException;
10 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
11 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
12 use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
13 use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
14 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
17 * Provides a container optimized for Drupal's needs.
19 * This container implementation is compatible with the default Symfony
20 * dependency injection container and similar to the Symfony ContainerBuilder
21 * class, but optimized for speed.
23 * It is based on a PHP array container definition dumped as a
24 * performance-optimized machine-readable format.
26 * The best way to initialize this container is to use a Container Builder,
27 * compile it and then retrieve the definition via
28 * \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper::getArray().
30 * The retrieved array can be cached safely and then passed to this container
31 * via the constructor.
33 * As the container is unfrozen by default, a second parameter can be passed to
34 * the container to "freeze" the parameter bag.
36 * This container is different in behavior from the default Symfony container in
39 * - It only allows lowercase service and parameter names, though it does only
40 * enforce it via assertions for performance reasons.
41 * - The following functions, that are not part of the interface, are explicitly
42 * not supported: getParameterBag(), isFrozen(), compile(),
43 * getAServiceWithAnIdByCamelCase().
44 * - The function getServiceIds() was added as it has a use-case in core and
46 * - Scopes are explicitly not allowed, because Symfony 2.8 has deprecated
47 * them and they will be removed in Symfony 3.0.
48 * - Synchronized services are explicitly not supported, because Symfony 2.8 has
49 * deprecated them and they will be removed in Symfony 3.0.
53 class Container implements IntrospectableContainerInterface, ResettableContainerInterface {
56 * The parameters of the container.
60 protected $parameters = [];
63 * The aliases of the container.
67 protected $aliases = [];
70 * The service definitions of the container.
74 protected $serviceDefinitions = [];
77 * The instantiated services.
81 protected $services = [];
84 * The instantiated private services.
88 protected $privateServices = [];
91 * The currently loading services.
95 protected $loading = [];
98 * Whether the container parameters can still be changed.
100 * For testing purposes the container needs to be changed.
104 protected $frozen = TRUE;
107 * Constructs a new Container instance.
109 * @param array $container_definition
110 * An array containing the following keys:
111 * - aliases: The aliases of the container.
112 * - parameters: The parameters of the container.
113 * - services: The service definitions of the container.
114 * - frozen: Whether the container definition came from a frozen
115 * container builder or not.
116 * - machine_format: Whether this container definition uses the optimized
117 * machine-readable container format.
119 public function __construct(array $container_definition = []) {
120 if (!empty($container_definition) && (!isset($container_definition['machine_format']) || $container_definition['machine_format'] !== TRUE)) {
121 throw new InvalidArgumentException('The non-optimized format is not supported by this class. Use an optimized machine-readable format instead, e.g. as produced by \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper.');
124 $this->aliases = isset($container_definition['aliases']) ? $container_definition['aliases'] : [];
125 $this->parameters = isset($container_definition['parameters']) ? $container_definition['parameters'] : [];
126 $this->serviceDefinitions = isset($container_definition['services']) ? $container_definition['services'] : [];
127 $this->frozen = isset($container_definition['frozen']) ? $container_definition['frozen'] : FALSE;
129 // Register the service_container with itself.
130 $this->services['service_container'] = $this;
136 public function get($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
137 if (isset($this->aliases[$id])) {
138 $id = $this->aliases[$id];
141 // Re-use shared service instance if it exists.
142 if (isset($this->services[$id]) || ($invalid_behavior === ContainerInterface::NULL_ON_INVALID_REFERENCE && array_key_exists($id, $this->services))) {
143 return $this->services[$id];
146 if (isset($this->loading[$id])) {
147 throw new ServiceCircularReferenceException($id, array_keys($this->loading));
150 $definition = isset($this->serviceDefinitions[$id]) ? $this->serviceDefinitions[$id] : NULL;
152 if (!$definition && $invalid_behavior === ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
154 throw new ServiceNotFoundException($id);
157 throw new ServiceNotFoundException($id, NULL, NULL, $this->getServiceAlternatives($id));
160 // In case something else than ContainerInterface::NULL_ON_INVALID_REFERENCE
161 // is used, the actual wanted behavior is to re-try getting the service at a
167 // Definition is a keyed array, so [0] is only defined when it is a
168 // serialized string.
169 if (isset($definition[0])) {
170 $definition = unserialize($definition);
173 // Now create the service.
174 $this->loading[$id] = TRUE;
177 $service = $this->createService($definition, $id);
179 catch (\Exception $e) {
180 unset($this->loading[$id]);
181 unset($this->services[$id]);
183 if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalid_behavior) {
190 unset($this->loading[$id]);
198 public function reset() {
199 if (!empty($this->scopedServices)) {
200 throw new LogicException('Resetting the container is not allowed when a scope is active.');
203 $this->services = [];
207 * Creates a service from a service definition.
209 * @param array $definition
210 * The service definition to create a service from.
212 * The service identifier, necessary so it can be shared if its public.
215 * The service described by the service definition.
217 * @throws \Symfony\Component\DependencyInjection\Exception\RuntimeException
218 * Thrown when the service is a synthetic service.
219 * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
220 * Thrown when the configurator callable in $definition['configurator'] is
221 * not actually a callable.
222 * @throws \ReflectionException
223 * Thrown when the service class takes more than 10 parameters to construct,
224 * and cannot be instantiated.
226 protected function createService(array $definition, $id) {
227 if (isset($definition['synthetic']) && $definition['synthetic'] === TRUE) {
228 throw new RuntimeException(sprintf('You have requested a synthetic service ("%s"). The service container does not know how to construct this service. The service will need to be set before it is first used.', $id));
232 if (isset($definition['arguments'])) {
233 $arguments = $definition['arguments'];
235 if ($arguments instanceof \stdClass) {
236 $arguments = $this->resolveServicesAndParameters($arguments);
240 if (isset($definition['file'])) {
241 $file = $this->frozen ? $definition['file'] : current($this->resolveServicesAndParameters([$definition['file']]));
245 if (isset($definition['factory'])) {
246 $factory = $definition['factory'];
247 if (is_array($factory)) {
248 $factory = $this->resolveServicesAndParameters([$factory[0], $factory[1]]);
250 elseif (!is_string($factory)) {
251 throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
254 $service = call_user_func_array($factory, $arguments);
257 $class = $this->frozen ? $definition['class'] : current($this->resolveServicesAndParameters([$definition['class']]));
258 $length = isset($definition['arguments_count']) ? $definition['arguments_count'] : count($arguments);
260 // Optimize class instantiation for services with up to 10 parameters as
261 // ReflectionClass is noticeably slow.
264 $service = new $class();
268 $service = new $class($arguments[0]);
272 $service = new $class($arguments[0], $arguments[1]);
276 $service = new $class($arguments[0], $arguments[1], $arguments[2]);
280 $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3]);
284 $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4]);
288 $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5]);
292 $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]);
296 $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7]);
300 $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8]);
304 $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8], $arguments[9]);
308 $r = new \ReflectionClass($class);
309 $service = $r->newInstanceArgs($arguments);
314 // Share the service if it is public.
315 if (!isset($definition['public']) || $definition['public'] !== FALSE) {
316 // Forward compatibility fix for Symfony 2.8 update.
317 if (!isset($definition['shared']) || $definition['shared'] !== FALSE) {
318 $this->services[$id] = $service;
322 if (isset($definition['calls'])) {
323 foreach ($definition['calls'] as $call) {
326 if (!empty($call[1])) {
327 $arguments = $call[1];
328 if ($arguments instanceof \stdClass) {
329 $arguments = $this->resolveServicesAndParameters($arguments);
332 call_user_func_array([$service, $method], $arguments);
336 if (isset($definition['properties'])) {
337 if ($definition['properties'] instanceof \stdClass) {
338 $definition['properties'] = $this->resolveServicesAndParameters($definition['properties']);
340 foreach ($definition['properties'] as $key => $value) {
341 $service->{$key} = $value;
345 if (isset($definition['configurator'])) {
346 $callable = $definition['configurator'];
347 if (is_array($callable)) {
348 $callable = $this->resolveServicesAndParameters($callable);
351 if (!is_callable($callable)) {
352 throw new InvalidArgumentException(sprintf('The configurator for class "%s" is not a callable.', get_class($service)));
355 call_user_func($callable, $service);
364 public function set($id, $service, $scope = ContainerInterface::SCOPE_CONTAINER) {
365 if (!in_array($scope, ['container', 'request']) || ('request' === $scope && 'request' !== $id)) {
366 @trigger_error('The concept of container scopes is deprecated since version 2.8 and will be removed in 3.0. Omit the third parameter.', E_USER_DEPRECATED);
369 $this->services[$id] = $service;
375 public function has($id) {
376 return isset($this->aliases[$id]) || isset($this->services[$id]) || isset($this->serviceDefinitions[$id]);
382 public function getParameter($name) {
383 if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) {
385 throw new ParameterNotFoundException($name);
388 throw new ParameterNotFoundException($name, NULL, NULL, NULL, $this->getParameterAlternatives($name));
391 return $this->parameters[$name];
397 public function hasParameter($name) {
398 return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters);
404 public function setParameter($name, $value) {
406 throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
409 $this->parameters[$name] = $value;
415 public function initialized($id) {
416 if (isset($this->aliases[$id])) {
417 $id = $this->aliases[$id];
420 return isset($this->services[$id]) || array_key_exists($id, $this->services);
424 * Resolves arguments that represent services or variables to the real values.
426 * @param array|\stdClass $arguments
427 * The arguments to resolve.
430 * The resolved arguments.
432 * @throws \Symfony\Component\DependencyInjection\Exception\RuntimeException
433 * If a parameter/service could not be resolved.
434 * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
435 * If an unknown type is met while resolving parameters and services.
437 protected function resolveServicesAndParameters($arguments) {
438 // Check if this collection needs to be resolved.
439 if ($arguments instanceof \stdClass) {
440 if ($arguments->type !== 'collection') {
441 throw new InvalidArgumentException(sprintf('Undefined type "%s" while resolving parameters and services.', $arguments->type));
443 // In case there is nothing to resolve, we are done here.
444 if (!$arguments->resolve) {
445 return $arguments->value;
447 $arguments = $arguments->value;
450 // Process the arguments.
451 foreach ($arguments as $key => $argument) {
452 // For this machine-optimized format, only \stdClass arguments are
453 // processed and resolved. All other values are kept as is.
454 if ($argument instanceof \stdClass) {
455 $type = $argument->type;
457 // Check for parameter.
458 if ($type == 'parameter') {
459 $name = $argument->name;
460 if (!isset($this->parameters[$name])) {
461 $arguments[$key] = $this->getParameter($name);
462 // This can never be reached as getParameter() throws an Exception,
463 // because we already checked that the parameter is not set above.
467 $argument = $arguments[$key] = $this->parameters[$name];
469 // In case there is not a machine readable value (e.g. a service)
470 // behind this resolved parameter, continue.
471 if (!($argument instanceof \stdClass)) {
476 $type = $argument->type;
480 if ($type == 'service') {
483 // Does the service already exist?
484 if (isset($this->aliases[$id])) {
485 $id = $this->aliases[$id];
488 if (isset($this->services[$id])) {
489 $arguments[$key] = $this->services[$id];
493 // Return the service.
494 $arguments[$key] = $this->get($id, $argument->invalidBehavior);
498 // Create private service.
499 elseif ($type == 'private_service') {
502 // Does the private service already exist.
503 if (isset($this->privateServices[$id])) {
504 $arguments[$key] = $this->privateServices[$id];
508 // Create the private service.
509 $arguments[$key] = $this->createService($argument->value, $id);
510 if ($argument->shared) {
511 $this->privateServices[$id] = $arguments[$key];
516 // Check for collection.
517 elseif ($type == 'collection') {
518 $value = $argument->value;
520 // Does this collection need resolving?
521 if ($argument->resolve) {
522 $arguments[$key] = $this->resolveServicesAndParameters($value);
525 $arguments[$key] = $value;
531 if ($type !== NULL) {
532 throw new InvalidArgumentException(sprintf('Undefined type "%s" while resolving parameters and services.', $type));
541 * Provides alternatives for a given array and key.
543 * @param string $search_key
544 * The search key to get alternatives for.
546 * The search space to search for alternatives in.
549 * An array of strings with suitable alternatives.
551 protected function getAlternatives($search_key, array $keys) {
553 foreach ($keys as $key) {
554 $lev = levenshtein($search_key, $key);
555 if ($lev <= strlen($search_key) / 3 || strpos($key, $search_key) !== FALSE) {
556 $alternatives[] = $key;
560 return $alternatives;
564 * Provides alternatives in case a service was not found.
567 * The service to get alternatives for.
570 * An array of strings with suitable alternatives.
572 protected function getServiceAlternatives($id) {
573 $all_service_keys = array_unique(array_merge(array_keys($this->services), array_keys($this->serviceDefinitions)));
574 return $this->getAlternatives($id, $all_service_keys);
578 * Provides alternatives in case a parameter was not found.
580 * @param string $name
581 * The parameter to get alternatives for.
584 * An array of strings with suitable alternatives.
586 protected function getParameterAlternatives($name) {
587 return $this->getAlternatives($name, array_keys($this->parameters));
594 public function enterScope($name) {
595 if ('request' !== $name) {
596 @trigger_error('The ' . __METHOD__ . ' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
599 throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
605 public function leaveScope($name) {
606 if ('request' !== $name) {
607 @trigger_error('The ' . __METHOD__ . ' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
610 throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
616 public function addScope(ScopeInterface $scope) {
618 $name = $scope->getName();
619 if ('request' !== $name) {
620 @trigger_error('The ' . __METHOD__ . ' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
622 throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
628 public function hasScope($name) {
629 if ('request' !== $name) {
630 @trigger_error('The ' . __METHOD__ . ' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
633 throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
639 public function isScopeActive($name) {
640 @trigger_error('The ' . __METHOD__ . ' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
642 throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
646 * Gets all defined service IDs.
649 * An array of all defined service IDs.
651 public function getServiceIds() {
652 return array_keys($this->serviceDefinitions + $this->services);
656 * Ensure that cloning doesn't work.
658 private function __clone()