Upgraded drupal core with security updates
[yaffs-website] / web / core / lib / Drupal / Component / DependencyInjection / Container.php
1 <?php
2
3 namespace Drupal\Component\DependencyInjection;
4
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;
15
16 /**
17  * Provides a container optimized for Drupal's needs.
18  *
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.
22  *
23  * It is based on a PHP array container definition dumped as a
24  * performance-optimized machine-readable format.
25  *
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().
29  *
30  * The retrieved array can be cached safely and then passed to this container
31  * via the constructor.
32  *
33  * As the container is unfrozen by default, a second parameter can be passed to
34  * the container to "freeze" the parameter bag.
35  *
36  * This container is different in behavior from the default Symfony container in
37  * the following ways:
38  *
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
45  *   contrib.
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.
50  *
51  * @ingroup container
52  */
53 class Container implements IntrospectableContainerInterface, ResettableContainerInterface {
54
55   /**
56    * The parameters of the container.
57    *
58    * @var array
59    */
60   protected $parameters = [];
61
62   /**
63    * The aliases of the container.
64    *
65    * @var array
66    */
67   protected $aliases = [];
68
69   /**
70    * The service definitions of the container.
71    *
72    * @var array
73    */
74   protected $serviceDefinitions = [];
75
76   /**
77    * The instantiated services.
78    *
79    * @var array
80    */
81   protected $services = [];
82
83   /**
84    * The instantiated private services.
85    *
86    * @var array
87    */
88   protected $privateServices = [];
89
90   /**
91    * The currently loading services.
92    *
93    * @var array
94    */
95   protected $loading = [];
96
97   /**
98    * Whether the container parameters can still be changed.
99    *
100    * For testing purposes the container needs to be changed.
101    *
102    * @var bool
103    */
104   protected $frozen = TRUE;
105
106   /**
107    * Constructs a new Container instance.
108    *
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.
118    */
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.');
122     }
123
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;
128
129     // Register the service_container with itself.
130     $this->services['service_container'] = $this;
131   }
132
133   /**
134    * {@inheritdoc}
135    */
136   public function get($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
137     if (isset($this->aliases[$id])) {
138       $id = $this->aliases[$id];
139     }
140
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];
144     }
145
146     if (isset($this->loading[$id])) {
147       throw new ServiceCircularReferenceException($id, array_keys($this->loading));
148     }
149
150     $definition = isset($this->serviceDefinitions[$id]) ? $this->serviceDefinitions[$id] : NULL;
151
152     if (!$definition && $invalid_behavior === ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
153       if (!$id) {
154         throw new ServiceNotFoundException($id);
155       }
156
157       throw new ServiceNotFoundException($id, NULL, NULL, $this->getServiceAlternatives($id));
158     }
159
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
162     // later point.
163     if (!$definition) {
164       return;
165     }
166
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);
171     }
172
173     // Now create the service.
174     $this->loading[$id] = TRUE;
175
176     try {
177       $service = $this->createService($definition, $id);
178     }
179     catch (\Exception $e) {
180       unset($this->loading[$id]);
181       unset($this->services[$id]);
182
183       if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalid_behavior) {
184         return;
185       }
186
187       throw $e;
188     }
189
190     unset($this->loading[$id]);
191
192     return $service;
193   }
194
195   /**
196    * {@inheritdoc}
197    */
198   public function reset() {
199     if (!empty($this->scopedServices)) {
200       throw new LogicException('Resetting the container is not allowed when a scope is active.');
201     }
202
203     $this->services = [];
204   }
205
206   /**
207    * Creates a service from a service definition.
208    *
209    * @param array $definition
210    *   The service definition to create a service from.
211    * @param string $id
212    *   The service identifier, necessary so it can be shared if its public.
213    *
214    * @return object
215    *   The service described by the service definition.
216    *
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.
225    */
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));
229     }
230
231     $arguments = [];
232     if (isset($definition['arguments'])) {
233       $arguments = $definition['arguments'];
234
235       if ($arguments instanceof \stdClass) {
236         $arguments = $this->resolveServicesAndParameters($arguments);
237       }
238     }
239
240     if (isset($definition['file'])) {
241       $file = $this->frozen ? $definition['file'] : current($this->resolveServicesAndParameters([$definition['file']]));
242       require_once $file;
243     }
244
245     if (isset($definition['factory'])) {
246       $factory = $definition['factory'];
247       if (is_array($factory)) {
248         $factory = $this->resolveServicesAndParameters([$factory[0], $factory[1]]);
249       }
250       elseif (!is_string($factory)) {
251         throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
252       }
253
254       $service = call_user_func_array($factory, $arguments);
255     }
256     else {
257       $class = $this->frozen ? $definition['class'] : current($this->resolveServicesAndParameters([$definition['class']]));
258       $length = isset($definition['arguments_count']) ? $definition['arguments_count'] : count($arguments);
259
260       // Optimize class instantiation for services with up to 10 parameters as
261       // ReflectionClass is noticeably slow.
262       switch ($length) {
263         case 0:
264           $service = new $class();
265           break;
266
267         case 1:
268           $service = new $class($arguments[0]);
269           break;
270
271         case 2:
272           $service = new $class($arguments[0], $arguments[1]);
273           break;
274
275         case 3:
276           $service = new $class($arguments[0], $arguments[1], $arguments[2]);
277           break;
278
279         case 4:
280           $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3]);
281           break;
282
283         case 5:
284           $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4]);
285           break;
286
287         case 6:
288           $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5]);
289           break;
290
291         case 7:
292           $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]);
293           break;
294
295         case 8:
296           $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7]);
297           break;
298
299         case 9:
300           $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8]);
301           break;
302
303         case 10:
304           $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8], $arguments[9]);
305           break;
306
307         default:
308           $r = new \ReflectionClass($class);
309           $service = $r->newInstanceArgs($arguments);
310           break;
311       }
312     }
313
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;
319       }
320     }
321
322     if (isset($definition['calls'])) {
323       foreach ($definition['calls'] as $call) {
324         $method = $call[0];
325         $arguments = [];
326         if (!empty($call[1])) {
327           $arguments = $call[1];
328           if ($arguments instanceof \stdClass) {
329             $arguments = $this->resolveServicesAndParameters($arguments);
330           }
331         }
332         call_user_func_array([$service, $method], $arguments);
333       }
334     }
335
336     if (isset($definition['properties'])) {
337       if ($definition['properties'] instanceof \stdClass) {
338         $definition['properties'] = $this->resolveServicesAndParameters($definition['properties']);
339       }
340       foreach ($definition['properties'] as $key => $value) {
341         $service->{$key} = $value;
342       }
343     }
344
345     if (isset($definition['configurator'])) {
346       $callable = $definition['configurator'];
347       if (is_array($callable)) {
348         $callable = $this->resolveServicesAndParameters($callable);
349       }
350
351       if (!is_callable($callable)) {
352         throw new InvalidArgumentException(sprintf('The configurator for class "%s" is not a callable.', get_class($service)));
353       }
354
355       call_user_func($callable, $service);
356     }
357
358     return $service;
359   }
360
361   /**
362    * {@inheritdoc}
363    */
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);
367     }
368
369     $this->services[$id] = $service;
370   }
371
372   /**
373    * {@inheritdoc}
374    */
375   public function has($id) {
376     return isset($this->aliases[$id]) || isset($this->services[$id]) || isset($this->serviceDefinitions[$id]);
377   }
378
379   /**
380    * {@inheritdoc}
381    */
382   public function getParameter($name) {
383     if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) {
384       if (!$name) {
385         throw new ParameterNotFoundException($name);
386       }
387
388       throw new ParameterNotFoundException($name, NULL, NULL, NULL, $this->getParameterAlternatives($name));
389     }
390
391     return $this->parameters[$name];
392   }
393
394   /**
395    * {@inheritdoc}
396    */
397   public function hasParameter($name) {
398     return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters);
399   }
400
401   /**
402    * {@inheritdoc}
403    */
404   public function setParameter($name, $value) {
405     if ($this->frozen) {
406       throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
407     }
408
409     $this->parameters[$name] = $value;
410   }
411
412   /**
413    * {@inheritdoc}
414    */
415   public function initialized($id) {
416     if (isset($this->aliases[$id])) {
417       $id = $this->aliases[$id];
418     }
419
420     return isset($this->services[$id]) || array_key_exists($id, $this->services);
421   }
422
423   /**
424    * Resolves arguments that represent services or variables to the real values.
425    *
426    * @param array|\stdClass $arguments
427    *   The arguments to resolve.
428    *
429    * @return array
430    *   The resolved arguments.
431    *
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.
436    */
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));
442       }
443       // In case there is nothing to resolve, we are done here.
444       if (!$arguments->resolve) {
445         return $arguments->value;
446       }
447       $arguments = $arguments->value;
448     }
449
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;
456
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.
464           }
465
466           // Update argument.
467           $argument = $arguments[$key] = $this->parameters[$name];
468
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)) {
472             continue;
473           }
474
475           // Fall through.
476           $type = $argument->type;
477         }
478
479         // Create a service.
480         if ($type == 'service') {
481           $id = $argument->id;
482
483           // Does the service already exist?
484           if (isset($this->aliases[$id])) {
485             $id = $this->aliases[$id];
486           }
487
488           if (isset($this->services[$id])) {
489             $arguments[$key] = $this->services[$id];
490             continue;
491           }
492
493           // Return the service.
494           $arguments[$key] = $this->get($id, $argument->invalidBehavior);
495
496           continue;
497         }
498         // Create private service.
499         elseif ($type == 'private_service') {
500           $id = $argument->id;
501
502           // Does the private service already exist.
503           if (isset($this->privateServices[$id])) {
504             $arguments[$key] = $this->privateServices[$id];
505             continue;
506           }
507
508           // Create the private service.
509           $arguments[$key] = $this->createService($argument->value, $id);
510           if ($argument->shared) {
511             $this->privateServices[$id] = $arguments[$key];
512           }
513
514           continue;
515         }
516         // Check for collection.
517         elseif ($type == 'collection') {
518           $value = $argument->value;
519
520           // Does this collection need resolving?
521           if ($argument->resolve) {
522             $arguments[$key] = $this->resolveServicesAndParameters($value);
523           }
524           else {
525             $arguments[$key] = $value;
526           }
527
528           continue;
529         }
530
531         if ($type !== NULL) {
532           throw new InvalidArgumentException(sprintf('Undefined type "%s" while resolving parameters and services.', $type));
533         }
534       }
535     }
536
537     return $arguments;
538   }
539
540   /**
541    * Provides alternatives for a given array and key.
542    *
543    * @param string $search_key
544    *   The search key to get alternatives for.
545    * @param array $keys
546    *   The search space to search for alternatives in.
547    *
548    * @return string[]
549    *   An array of strings with suitable alternatives.
550    */
551   protected function getAlternatives($search_key, array $keys) {
552     $alternatives = [];
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;
557       }
558     }
559
560     return $alternatives;
561   }
562
563   /**
564    * Provides alternatives in case a service was not found.
565    *
566    * @param string $id
567    *   The service to get alternatives for.
568    *
569    * @return string[]
570    *   An array of strings with suitable alternatives.
571    */
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);
575   }
576
577   /**
578    * Provides alternatives in case a parameter was not found.
579    *
580    * @param string $name
581    *   The parameter to get alternatives for.
582    *
583    * @return string[]
584    *   An array of strings with suitable alternatives.
585    */
586   protected function getParameterAlternatives($name) {
587     return $this->getAlternatives($name, array_keys($this->parameters));
588   }
589
590
591   /**
592    * {@inheritdoc}
593    */
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);
597     }
598
599     throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
600   }
601
602   /**
603    * {@inheritdoc}
604    */
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);
608     }
609
610     throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
611   }
612
613   /**
614    * {@inheritdoc}
615    */
616   public function addScope(ScopeInterface $scope) {
617
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);
621     }
622     throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
623   }
624
625   /**
626    * {@inheritdoc}
627    */
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);
631     }
632
633     throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
634   }
635
636   /**
637    * {@inheritdoc}
638    */
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);
641
642     throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
643   }
644
645   /**
646    * Gets all defined service IDs.
647    *
648    * @return array
649    *   An array of all defined service IDs.
650    */
651   public function getServiceIds() {
652     return array_keys($this->serviceDefinitions + $this->services);
653   }
654
655   /**
656    * Ensure that cloning doesn't work.
657    */
658   private function __clone()
659   {
660   }
661
662 }