Newer
Older
<?php
namespace Drupal\Component\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Contracts\Service\ResetInterface;
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Provides a container optimized for Drupal's needs.
*
* This container implementation is compatible with the default Symfony
* dependency injection container and similar to the Symfony ContainerBuilder
* class, but optimized for speed.
*
* It is based on a PHP array container definition dumped as a
* performance-optimized machine-readable format.
*
* The best way to initialize this container is to use a Container Builder,
* compile it and then retrieve the definition via
* \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper::getArray().
*
* The retrieved array can be cached safely and then passed to this container
* via the constructor.
*
* As the container is unfrozen by default, a second parameter can be passed to
* the container to "freeze" the parameter bag.
*
* This container is different in behavior from the default Symfony container in
* the following ways:
*
* - It only allows lowercase service and parameter names, though it does only
* enforce it via assertions for performance reasons.
* - The following functions, that are not part of the interface, are explicitly
* not supported: getParameterBag(), isFrozen(), compile(),
* getAServiceWithAnIdByCamelCase().
* - The function getServiceIds() was added as it has a use-case in core and
* contrib.
*
* @ingroup container
*/
class Container implements ContainerInterface, ResetInterface {
/**
* The parameters of the container.
*
* @var array
*/
protected $parameters = [];
/**
* The aliases of the container.
*
* @var array
*/
protected $aliases = [];
/**
* The service definitions of the container.
*
* @var array
*/
protected $serviceDefinitions = [];
/**
* The instantiated services.
*
* @var array
*/
protected $services = [];
/**
* The instantiated private services.
*
* @var array
*/
protected $privateServices = [];
/**
* The currently loading services.
*
* @var array
*/
protected $loading = [];
/**
* Whether the container parameters can still be changed.
*
* For testing purposes the container needs to be changed.
*
* @var bool
*/
protected $frozen = TRUE;
/**
* Constructs a new Container instance.
*
* @param array $container_definition
* An array containing the following keys:
* - aliases: The aliases of the container.
* - parameters: The parameters of the container.
* - services: The service definitions of the container.
* - frozen: Whether the container definition came from a frozen
* container builder or not.
* - machine_format: Whether this container definition uses the optimized
* machine-readable container format.
*/
public function __construct(array $container_definition = []) {
if (!empty($container_definition) && (!isset($container_definition['machine_format']) || $container_definition['machine_format'] !== TRUE)) {
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.');
}
$this->aliases = $container_definition['aliases'] ?? [];
$this->parameters = $container_definition['parameters'] ?? [];
$this->serviceDefinitions = $container_definition['services'] ?? [];
$this->frozen = $container_definition['frozen'] ?? FALSE;
// Register the service_container with itself.
$this->services['service_container'] = $this;
}
/**
* {@inheritdoc}
*/
public function get($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {

Lee Rowlands
committed
if ($this->hasParameter('_deprecated_service_list')) {
if ($deprecation = $this->getParameter('_deprecated_service_list')[$id] ?? '') {
@trigger_error($deprecation, E_USER_DEPRECATED);
}
}
if (isset($this->aliases[$id])) {
$id = $this->aliases[$id];
}
// Re-use shared service instance if it exists.
if (isset($this->services[$id]) || ($invalid_behavior === ContainerInterface::NULL_ON_INVALID_REFERENCE && array_key_exists($id, $this->services))) {
return $this->services[$id];
}
if (isset($this->loading[$id])) {
throw new ServiceCircularReferenceException($id, array_keys($this->loading));
}
$definition = $this->serviceDefinitions[$id] ?? NULL;
if (!$definition && $invalid_behavior === ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
if (!$id) {

Lee Rowlands
committed
throw new ServiceNotFoundException('');
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
}
throw new ServiceNotFoundException($id, NULL, NULL, $this->getServiceAlternatives($id));
}
// In case something else than ContainerInterface::NULL_ON_INVALID_REFERENCE
// is used, the actual wanted behavior is to re-try getting the service at a
// later point.
if (!$definition) {
return;
}
// Definition is a keyed array, so [0] is only defined when it is a
// serialized string.
if (isset($definition[0])) {
$definition = unserialize($definition);
}
// Now create the service.
$this->loading[$id] = TRUE;
try {
$service = $this->createService($definition, $id);
}
catch (\Exception $e) {
unset($this->loading[$id]);

catch
committed
unset($this->services[$id]);
if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalid_behavior) {
return;
}
throw $e;
}
unset($this->loading[$id]);
return $service;
}

catch
committed
/**

Lee Rowlands
committed
* Resets shared services from the container.
*
* The container is not intended to be used again after being reset in a
* normal workflow. This method is meant as a way to release references for
* ref-counting. A subsequent call to ContainerInterface::get() will recreate
* a new instance of the shared service.

catch
committed
*/
public function reset() {
if (!empty($this->scopedServices)) {
throw new LogicException('Resetting the container is not allowed when a scope is active.');
}
$this->services = [];
}
/**
* Creates a service from a service definition.
*
* @param array $definition
* The service definition to create a service from.
* @param string $id
* The service identifier, necessary so it can be shared if its public.
*
* @return object
* The service described by the service definition.
*
* @throws \Symfony\Component\DependencyInjection\Exception\RuntimeException
* Thrown when the service is a synthetic service.
* @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* Thrown when the configurator callable in $definition['configurator'] is
* not actually a callable.
* @throws \ReflectionException
* Thrown when the service class takes more than 10 parameters to construct,
* and cannot be instantiated.
*/
protected function createService(array $definition, $id) {
if (isset($definition['synthetic']) && $definition['synthetic'] === TRUE) {
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));
}
$arguments = [];
if (isset($definition['arguments'])) {
$arguments = $definition['arguments'];
if ($arguments instanceof \stdClass) {
$arguments = $this->resolveServicesAndParameters($arguments);
}
}
if (isset($definition['file'])) {
$file = $this->frozen ? $definition['file'] : current($this->resolveServicesAndParameters([$definition['file']]));
require_once $file;
}
if (isset($definition['factory'])) {
$factory = $definition['factory'];
if (is_array($factory)) {
$factory = $this->resolveServicesAndParameters([$factory[0], $factory[1]]);
}
elseif (!is_string($factory)) {
throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
}
$service = call_user_func_array($factory, $arguments);
}
else {
$class = $this->frozen ? $definition['class'] : current($this->resolveServicesAndParameters([$definition['class']]));
$service = new $class(...$arguments);
}
if (!isset($definition['shared']) || $definition['shared'] !== FALSE) {
$this->services[$id] = $service;
}
if (isset($definition['calls'])) {
foreach ($definition['calls'] as $call) {
$method = $call[0];
$arguments = [];
if (!empty($call[1])) {
$arguments = $call[1];
if ($arguments instanceof \stdClass) {
$arguments = $this->resolveServicesAndParameters($arguments);
}
}
call_user_func_array([$service, $method], $arguments);
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
}
}
if (isset($definition['properties'])) {
if ($definition['properties'] instanceof \stdClass) {
$definition['properties'] = $this->resolveServicesAndParameters($definition['properties']);
}
foreach ($definition['properties'] as $key => $value) {
$service->{$key} = $value;
}
}
if (isset($definition['configurator'])) {
$callable = $definition['configurator'];
if (is_array($callable)) {
$callable = $this->resolveServicesAndParameters($callable);
}
if (!is_callable($callable)) {
throw new InvalidArgumentException(sprintf('The configurator for class "%s" is not a callable.', get_class($service)));
}
call_user_func($callable, $service);
}
return $service;
}
/**
* {@inheritdoc}
*/
public function set($id, $service) {
$this->services[$id] = $service;
}
/**
* {@inheritdoc}
*/
public function has($id) {
return isset($this->aliases[$id]) || isset($this->services[$id]) || isset($this->serviceDefinitions[$id]);
}
/**
* {@inheritdoc}
*/
public function getParameter($name) {
if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters))) {
if (!$name) {

Lee Rowlands
committed
throw new ParameterNotFoundException('');
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
}
throw new ParameterNotFoundException($name, NULL, NULL, NULL, $this->getParameterAlternatives($name));
}
return $this->parameters[$name];
}
/**
* {@inheritdoc}
*/
public function hasParameter($name) {
return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters);
}
/**
* {@inheritdoc}
*/
public function setParameter($name, $value) {
if ($this->frozen) {
throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
}
$this->parameters[$name] = $value;
}
/**
* {@inheritdoc}
*/
public function initialized($id) {
if (isset($this->aliases[$id])) {
$id = $this->aliases[$id];
}
return isset($this->services[$id]) || array_key_exists($id, $this->services);
}
/**
* Resolves arguments that represent services or variables to the real values.
*

Alex Pott
committed
* @param array|object $arguments
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
* The arguments to resolve.
*
* @return array
* The resolved arguments.
*
* @throws \Symfony\Component\DependencyInjection\Exception\RuntimeException
* If a parameter/service could not be resolved.
* @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* If an unknown type is met while resolving parameters and services.
*/
protected function resolveServicesAndParameters($arguments) {
// Check if this collection needs to be resolved.
if ($arguments instanceof \stdClass) {
if ($arguments->type !== 'collection') {
throw new InvalidArgumentException(sprintf('Undefined type "%s" while resolving parameters and services.', $arguments->type));
}
// In case there is nothing to resolve, we are done here.
if (!$arguments->resolve) {
return $arguments->value;
}
$arguments = $arguments->value;
}
// Process the arguments.
foreach ($arguments as $key => $argument) {
// For this machine-optimized format, only \stdClass arguments are
// processed and resolved. All other values are kept as is.
if ($argument instanceof \stdClass) {
$type = $argument->type;
// Check for parameter.
if ($type == 'parameter') {
$name = $argument->name;
if (!isset($this->parameters[$name])) {
$arguments[$key] = $this->getParameter($name);
// This can never be reached as getParameter() throws an Exception,
// because we already checked that the parameter is not set above.
}
// Update argument.
$argument = $arguments[$key] = $this->parameters[$name];
// In case there is not a machine readable value (e.g. a service)
// behind this resolved parameter, continue.
if (!($argument instanceof \stdClass)) {
continue;
}
// Fall through.
$type = $argument->type;
}
// Create a service.
if ($type == 'service') {
$id = $argument->id;
// Does the service already exist?
if (isset($this->aliases[$id])) {
$id = $this->aliases[$id];
}
if (isset($this->services[$id])) {
$arguments[$key] = $this->services[$id];
continue;
}
// Return the service.
$arguments[$key] = $this->get($id, $argument->invalidBehavior);
continue;
}
// Create private service.
elseif ($type == 'private_service') {
$id = $argument->id;
// Does the private service already exist.
if (isset($this->privateServices[$id])) {
$arguments[$key] = $this->privateServices[$id];
continue;
}
// Create the private service.
$arguments[$key] = $this->createService($argument->value, $id);
if ($argument->shared) {
$this->privateServices[$id] = $arguments[$key];
}
continue;
}
// Check for collection.
elseif ($type == 'collection') {
$value = $argument->value;
// Does this collection need resolving?
if ($argument->resolve) {
$arguments[$key] = $this->resolveServicesAndParameters($value);
}
else {
$arguments[$key] = $value;
}
continue;
}

catch
committed
elseif ($type == 'raw') {
$arguments[$key] = $argument->value;
continue;
}
if ($type !== NULL) {
throw new InvalidArgumentException(sprintf('Undefined type "%s" while resolving parameters and services.', $type));
}
}
}
return $arguments;
}
/**
* Provides alternatives for a given array and key.
*
* @param string $search_key
* The search key to get alternatives for.
* @param array $keys
* The search space to search for alternatives in.
*
* @return string[]
* An array of strings with suitable alternatives.
*/
protected function getAlternatives($search_key, array $keys) {
$alternatives = [];
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
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
foreach ($keys as $key) {
$lev = levenshtein($search_key, $key);
if ($lev <= strlen($search_key) / 3 || strpos($key, $search_key) !== FALSE) {
$alternatives[] = $key;
}
}
return $alternatives;
}
/**
* Provides alternatives in case a service was not found.
*
* @param string $id
* The service to get alternatives for.
*
* @return string[]
* An array of strings with suitable alternatives.
*/
protected function getServiceAlternatives($id) {
$all_service_keys = array_unique(array_merge(array_keys($this->services), array_keys($this->serviceDefinitions)));
return $this->getAlternatives($id, $all_service_keys);
}
/**
* Provides alternatives in case a parameter was not found.
*
* @param string $name
* The parameter to get alternatives for.
*
* @return string[]
* An array of strings with suitable alternatives.
*/
protected function getParameterAlternatives($name) {
return $this->getAlternatives($name, array_keys($this->parameters));
}
/**
* Gets all defined service IDs.
*
* @return array
* An array of all defined service IDs.
*/
public function getServiceIds() {
return array_keys($this->serviceDefinitions + $this->services);
}

catch
committed
/**
* Ensure that cloning doesn't work.
*/
private function __clone() {

catch
committed
}