Update to Drupal 8.0.0-beta15. For more information, see: https://www.drupal.org/node/2563023

This commit is contained in:
Pantheon Automation 2015-09-04 13:20:09 -07:00 committed by Greg Anderson
parent 2720a9ec4b
commit f3791f1da3
1898 changed files with 54300 additions and 11481 deletions

View file

@ -0,0 +1,629 @@
<?php
/**
* @file
* Contains \Drupal\Component\DependencyInjection\Container.
*/
namespace Drupal\Component\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\IntrospectableContainerInterface;
use Symfony\Component\DependencyInjection\ScopeInterface;
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;
/**
* 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.
* - Scopes are explicitly not allowed, because Symfony 2.8 has deprecated
* them and they will be removed in Symfony 3.0.
* - Synchronized services are explicitly not supported, because Symfony 2.8 has
* deprecated them and they will be removed in Symfony 3.0.
*
* @ingroup container
*/
class Container implements IntrospectableContainerInterface {
/**
* The parameters of the container.
*
* @var array
*/
protected $parameters = array();
/**
* The aliases of the container.
*
* @var array
*/
protected $aliases = array();
/**
* The service definitions of the container.
*
* @var array
*/
protected $serviceDefinitions = array();
/**
* The instantiated services.
*
* @var array
*/
protected $services = array();
/**
* The instantiated private services.
*
* @var array
*/
protected $privateServices = array();
/**
* The currently loading services.
*
* @var array
*/
protected $loading = array();
/**
* 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 = array()) {
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 = isset($container_definition['aliases']) ? $container_definition['aliases'] : array();
$this->parameters = isset($container_definition['parameters']) ? $container_definition['parameters'] : array();
$this->serviceDefinitions = isset($container_definition['services']) ? $container_definition['services'] : array();
$this->frozen = isset($container_definition['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) {
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 = isset($this->serviceDefinitions[$id]) ? $this->serviceDefinitions[$id] : NULL;
if (!$definition && $invalid_behavior === ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
if (!$id) {
throw new ServiceNotFoundException($id);
}
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]);
// Remove a potentially shared service that was constructed incompletely.
if (array_key_exists($id, $this->services)) {
unset($this->services[$id]);
}
if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalid_behavior) {
return;
}
throw $e;
}
unset($this->loading[$id]);
return $service;
}
/**
* 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 = array();
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(array($definition['file'])));
require_once $file;
}
if (isset($definition['factory'])) {
$factory = $definition['factory'];
if (is_array($factory)) {
$factory = $this->resolveServicesAndParameters(array($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(array($definition['class'])));
$length = isset($definition['arguments_count']) ? $definition['arguments_count'] : count($arguments);
// Optimize class instantiation for services with up to 10 parameters as
// ReflectionClass is noticeably slow.
switch ($length) {
case 0:
$service = new $class();
break;
case 1:
$service = new $class($arguments[0]);
break;
case 2:
$service = new $class($arguments[0], $arguments[1]);
break;
case 3:
$service = new $class($arguments[0], $arguments[1], $arguments[2]);
break;
case 4:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3]);
break;
case 5:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4]);
break;
case 6:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5]);
break;
case 7:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]);
break;
case 8:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7]);
break;
case 9:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8]);
break;
case 10:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8], $arguments[9]);
break;
default:
$r = new \ReflectionClass($class);
$service = $r->newInstanceArgs($arguments);
break;
}
}
// Share the service if it is public.
if (!isset($definition['public']) || $definition['public'] !== FALSE) {
// Forward compatibility fix for Symfony 2.8 update.
if (!isset($definition['shared']) || $definition['shared'] !== FALSE) {
$this->services[$id] = $service;
}
}
if (isset($definition['calls'])) {
foreach ($definition['calls'] as $call) {
$method = $call[0];
$arguments = array();
if (!empty($call[1])) {
$arguments = $call[1];
if ($arguments instanceof \stdClass) {
$arguments = $this->resolveServicesAndParameters($arguments);
}
}
call_user_func_array(array($service, $method), $arguments);
}
}
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, $scope = ContainerInterface::SCOPE_CONTAINER) {
$this->services[$id] = $service;
}
/**
* {@inheritdoc}
*/
public function has($id) {
return 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) {
throw new ParameterNotFoundException($name);
}
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.
*
* @param array|\stdClass $arguments
* 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;
}
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 = array();
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));
}
/**
* {@inheritdoc}
*/
public function enterScope($name) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* {@inheritdoc}
*/
public function leaveScope($name) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* {@inheritdoc}
*/
public function addScope(ScopeInterface $scope) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* {@inheritdoc}
*/
public function hasScope($name) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* {@inheritdoc}
*/
public function isScopeActive($name) {
throw new \BadMethodCallException(sprintf("'%s' is not supported by Drupal 8.", __FUNCTION__));
}
/**
* Gets all defined service IDs.
*
* @return array
* An array of all defined service IDs.
*/
public function getServiceIds() {
return array_keys($this->serviceDefinitions + $this->services);
}
}

View file

@ -0,0 +1,513 @@
<?php
/**
* @file
* Contains \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper.
*/
namespace Drupal\Component\DependencyInjection\Dumper;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Dumper\Dumper;
use Symfony\Component\ExpressionLanguage\Expression;
/**
* OptimizedPhpArrayDumper dumps a service container as a serialized PHP array.
*
* The format of this dumper is very similar to the internal structure of the
* ContainerBuilder, but based on PHP arrays and \stdClass objects instead of
* rich value objects for performance reasons.
*
* By removing the abstraction and optimizing some cases like deep collections,
* fewer classes need to be loaded, fewer function calls need to be executed and
* fewer run time checks need to be made.
*
* In addition to that, this container dumper treats private services as
* strictly private with their own private services storage, whereas in the
* Symfony service container builder and PHP dumper, shared private services can
* still be retrieved via get() from the container.
*
* It is machine-optimized, for a human-readable version based on this one see
* \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper.
*
* @see \Drupal\Component\DependencyInjection\Container
*/
class OptimizedPhpArrayDumper extends Dumper {
/**
* Whether to serialize service definitions or not.
*
* Service definitions are serialized by default to avoid having to
* unserialize the whole container on loading time, which improves early
* bootstrap performance for e.g. the page cache.
*
* @var bool
*/
protected $serialize = TRUE;
/**
* {@inheritdoc}
*/
public function dump(array $options = array()) {
return serialize($this->getArray());
}
/**
* Gets the service container definition as a PHP array.
*
* @return array
* A PHP array representation of the service container.
*/
public function getArray() {
$definition = array();
$definition['aliases'] = $this->getAliases();
$definition['parameters'] = $this->getParameters();
$definition['services'] = $this->getServiceDefinitions();
$definition['frozen'] = $this->container->isFrozen();
$definition['machine_format'] = $this->supportsMachineFormat();
return $definition;
}
/**
* Gets the aliases as a PHP array.
*
* @return array
* The aliases.
*/
protected function getAliases() {
$alias_definitions = array();
$aliases = $this->container->getAliases();
foreach ($aliases as $alias => $id) {
$id = (string) $id;
while (isset($aliases[$id])) {
$id = (string) $aliases[$id];
}
$alias_definitions[$alias] = $id;
}
return $alias_definitions;
}
/**
* Gets parameters of the container as a PHP array.
*
* @return array
* The escaped and prepared parameters of the container.
*/
protected function getParameters() {
if (!$this->container->getParameterBag()->all()) {
return array();
}
$parameters = $this->container->getParameterBag()->all();
$is_frozen = $this->container->isFrozen();
return $this->prepareParameters($parameters, $is_frozen);
}
/**
* Gets services of the container as a PHP array.
*
* @return array
* The service definitions.
*/
protected function getServiceDefinitions() {
if (!$this->container->getDefinitions()) {
return array();
}
$services = array();
foreach ($this->container->getDefinitions() as $id => $definition) {
// Only store public service definitions, references to shared private
// services are handled in ::getReferenceCall().
if ($definition->isPublic()) {
$service_definition = $this->getServiceDefinition($definition);
$services[$id] = $this->serialize ? serialize($service_definition) : $service_definition;
}
}
return $services;
}
/**
* Prepares parameters for the PHP array dumping.
*
* @param array $parameters
* An array of parameters.
* @param bool $escape
* Whether keys with '%' should be escaped or not.
*
* @return array
* An array of prepared parameters.
*/
protected function prepareParameters(array $parameters, $escape = TRUE) {
$filtered = array();
foreach ($parameters as $key => $value) {
if (is_array($value)) {
$value = $this->prepareParameters($value, $escape);
}
elseif ($value instanceof Reference) {
$value = $this->dumpValue($value);
}
$filtered[$key] = $value;
}
return $escape ? $this->escape($filtered) : $filtered;
}
/**
* Escapes parameters.
*
* @param array $parameters
* The parameters to escape for '%' characters.
*
* @return array
* The escaped parameters.
*/
protected function escape(array $parameters) {
$args = array();
foreach ($parameters as $key => $value) {
if (is_array($value)) {
$args[$key] = $this->escape($value);
}
elseif (is_string($value)) {
$args[$key] = str_replace('%', '%%', $value);
}
else {
$args[$key] = $value;
}
}
return $args;
}
/**
* Gets a service definition as PHP array.
*
* @param \Symfony\Component\DependencyInjection\Definition $definition
* The definition to process.
*
* @return array
* The service definition as PHP array.
*
* @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* Thrown when the definition is marked as decorated, or with an explicit
* scope different from SCOPE_CONTAINER and SCOPE_PROTOTYPE.
*/
protected function getServiceDefinition(Definition $definition) {
$service = array();
if ($definition->getClass()) {
$service['class'] = $definition->getClass();
}
if (!$definition->isPublic()) {
$service['public'] = FALSE;
}
if ($definition->getFile()) {
$service['file'] = $definition->getFile();
}
if ($definition->isSynthetic()) {
$service['synthetic'] = TRUE;
}
if ($definition->isLazy()) {
$service['lazy'] = TRUE;
}
if ($definition->getArguments()) {
$arguments = $definition->getArguments();
$service['arguments'] = $this->dumpCollection($arguments);
$service['arguments_count'] = count($arguments);
}
else {
$service['arguments_count'] = 0;
}
if ($definition->getProperties()) {
$service['properties'] = $this->dumpCollection($definition->getProperties());
}
if ($definition->getMethodCalls()) {
$service['calls'] = $this->dumpMethodCalls($definition->getMethodCalls());
}
if (($scope = $definition->getScope()) !== ContainerInterface::SCOPE_CONTAINER) {
if ($scope === ContainerInterface::SCOPE_PROTOTYPE) {
// Scope prototype has been replaced with 'shared' => FALSE.
// This is a Symfony 2.8 forward compatibility fix.
// Reference: https://github.com/symfony/symfony/blob/2.8/UPGRADE-2.8.md#dependencyinjection
$service['shared'] = FALSE;
}
else {
throw new InvalidArgumentException("The 'scope' definition is deprecated in Symfony 3.0 and not supported by Drupal 8.");
}
}
if (($decorated = $definition->getDecoratedService()) !== NULL) {
throw new InvalidArgumentException("The 'decorated' definition is not supported by the Drupal 8 run-time container. The Container Builder should have resolved that during the DecoratorServicePass compiler pass.");
}
if ($callable = $definition->getFactory()) {
$service['factory'] = $this->dumpCallable($callable);
}
if ($callable = $definition->getConfigurator()) {
$service['configurator'] = $this->dumpCallable($callable);
}
return $service;
}
/**
* Dumps method calls to a PHP array.
*
* @param array $calls
* An array of method calls.
*
* @return array
* The PHP array representation of the method calls.
*/
protected function dumpMethodCalls(array $calls) {
$code = array();
foreach ($calls as $key => $call) {
$method = $call[0];
$arguments = array();
if (!empty($call[1])) {
$arguments = $this->dumpCollection($call[1]);
}
$code[$key] = [$method, $arguments];
}
return $code;
}
/**
* Dumps a collection to a PHP array.
*
* @param mixed $collection
* A collection to process.
* @param bool &$resolve
* Used for passing the information to the caller whether the given
* collection needed to be resolved or not. This is used for optimizing
* deep arrays that don't need to be traversed.
*
* @return \stdClass|array
* The collection in a suitable format.
*/
protected function dumpCollection($collection, &$resolve = FALSE) {
$code = array();
foreach ($collection as $key => $value) {
if (is_array($value)) {
$resolve_collection = FALSE;
$code[$key] = $this->dumpCollection($value, $resolve_collection);
if ($resolve_collection) {
$resolve = TRUE;
}
}
else {
if (is_object($value)) {
$resolve = TRUE;
}
$code[$key] = $this->dumpValue($value);
}
}
if (!$resolve) {
return $collection;
}
return (object) array(
'type' => 'collection',
'value' => $code,
'resolve' => $resolve,
);
}
/**
* Dumps callable to a PHP array.
*
* @param array|callable $callable
* The callable to process.
*
* @return callable
* The processed callable.
*/
protected function dumpCallable($callable) {
if (is_array($callable)) {
$callable[0] = $this->dumpValue($callable[0]);
$callable = array($callable[0], $callable[1]);
}
return $callable;
}
/**
* Gets a private service definition in a suitable format.
*
* @param string $id
* The ID of the service to get a private definition for.
* @param \Symfony\Component\DependencyInjection\Definition $definition
* The definition to process.
* @param bool $shared
* (optional) Whether the service will be shared with others.
* By default this parameter is FALSE.
*
* @return \stdClass
* A very lightweight private service value object.
*/
protected function getPrivateServiceCall($id, Definition $definition, $shared = FALSE) {
$service_definition = $this->getServiceDefinition($definition);
if (!$id) {
$hash = hash('sha1', serialize($service_definition));
$id = 'private__' . $hash;
}
return (object) array(
'type' => 'private_service',
'id' => $id,
'value' => $service_definition,
'shared' => $shared,
);
}
/**
* Dumps the value to PHP array format.
*
* @param mixed $value
* The value to dump.
*
* @return mixed
* The dumped value in a suitable format.
*
* @throws RuntimeException
* When trying to dump object or resource.
*/
protected function dumpValue($value) {
if (is_array($value)) {
$code = array();
foreach ($value as $k => $v) {
$code[$k] = $this->dumpValue($v);
}
return $code;
}
elseif ($value instanceof Reference) {
return $this->getReferenceCall((string) $value, $value);
}
elseif ($value instanceof Definition) {
return $this->getPrivateServiceCall(NULL, $value);
}
elseif ($value instanceof Parameter) {
return $this->getParameterCall((string) $value);
}
elseif ($value instanceof Expression) {
throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
}
elseif (is_object($value)) {
// Drupal specific: Instantiated objects have a _serviceId parameter.
if (isset($value->_serviceId)) {
return $this->getReferenceCall($value->_serviceId);
}
throw new RuntimeException('Unable to dump a service container if a parameter is an object without _serviceId.');
}
elseif (is_resource($value)) {
throw new RuntimeException('Unable to dump a service container if a parameter is a resource.');
}
return $value;
}
/**
* Gets a service reference for a reference in a suitable PHP array format.
*
* The main difference is that this function treats references to private
* services differently and returns a private service reference instead of
* a normal reference.
*
* @param string $id
* The ID of the service to get a reference for.
* @param \Symfony\Component\DependencyInjection\Reference|NULL $reference
* (optional) The reference object to process; needed to get the invalid
* behavior value.
*
* @return string|\stdClass
* A suitable representation of the service reference.
*/
protected function getReferenceCall($id, Reference $reference = NULL) {
$invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
if ($reference !== NULL) {
$invalid_behavior = $reference->getInvalidBehavior();
}
// Private shared service.
$definition = $this->container->getDefinition($id);
if (!$definition->isPublic()) {
// The ContainerBuilder does not share a private service, but this means a
// new service is instantiated every time. Use a private shared service to
// circumvent the problem.
return $this->getPrivateServiceCall($id, $definition, TRUE);
}
return $this->getServiceCall($id, $invalid_behavior);
}
/**
* Gets a service reference for an ID in a suitable PHP array format.
*
* @param string $id
* The ID of the service to get a reference for.
* @param int $invalid_behavior
* (optional) The invalid behavior of the service.
*
* @return string|\stdClass
* A suitable representation of the service reference.
*/
protected function getServiceCall($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
return (object) array(
'type' => 'service',
'id' => $id,
'invalidBehavior' => $invalid_behavior,
);
}
/**
* Gets a parameter reference in a suitable PHP array format.
*
* @param string $name
* The name of the parameter to get a reference for.
*
* @return string|\stdClass
* A suitable representation of the parameter reference.
*/
protected function getParameterCall($name) {
return (object) array(
'type' => 'parameter',
'name' => $name,
);
}
/**
* Whether this supports the machine-optimized format or not.
*
* @return bool
* TRUE if this supports machine-optimized format, FALSE otherwise.
*/
protected function supportsMachineFormat() {
return TRUE;
}
}

View file

@ -0,0 +1,77 @@
<?php
/**
* @file
* Contains \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper.
*/
namespace Drupal\Component\DependencyInjection\Dumper;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* PhpArrayDumper dumps a service container as a PHP array.
*
* The format of this dumper is a human-readable serialized PHP array, which is
* very similar to the YAML based format, but based on PHP arrays instead of
* YAML strings.
*
* It is human-readable, for a machine-optimized version based on this one see
* \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper.
*
* @see \Drupal\Component\DependencyInjection\PhpArrayContainer
*/
class PhpArrayDumper extends OptimizedPhpArrayDumper {
/**
* {@inheritdoc}
*/
public function getArray() {
$this->serialize = FALSE;
return parent::getArray();
}
/**
* {@inheritdoc}
*/
protected function dumpCollection($collection, &$resolve = FALSE) {
$code = array();
foreach ($collection as $key => $value) {
if (is_array($value)) {
$code[$key] = $this->dumpCollection($value);
}
else {
$code[$key] = $this->dumpValue($value);
}
}
return $code;
}
/**
* {@inheritdoc}
*/
protected function getServiceCall($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
if ($invalid_behavior !== ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
return '@?' . $id;
}
return '@' . $id;
}
/**
* {@inheritdoc}
*/
protected function getParameterCall($name) {
return '%' . $name . '%';
}
/**
* {@inheritdoc}
*/
protected function supportsMachineFormat() {
return FALSE;
}
}

View file

@ -0,0 +1,276 @@
<?php
/**
* @file
* Contains \Drupal\Component\DependencyInjection\PhpArrayContainer.
*/
namespace Drupal\Component\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
/**
* 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 human-readable PHP array container definition with a
* structure very similar to the YAML container definition.
*
* @see \Drupal\Component\DependencyInjection\Container
* @see \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper
* @see \Drupal\Component\DependencyInjection\DependencySerializationTrait
*
* @ingroup container
*/
class PhpArrayContainer extends Container {
/**
* {@inheritdoc}
*/
public function __construct(array $container_definition = array()) {
if (isset($container_definition['machine_format']) && $container_definition['machine_format'] === TRUE) {
throw new InvalidArgumentException('The machine-optimized format is not supported by this class. Use a human-readable format instead, e.g. as produced by \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper.');
}
// Do not call the parent's constructor as it would bail on the
// machine-optimized format.
$this->aliases = isset($container_definition['aliases']) ? $container_definition['aliases'] : array();
$this->parameters = isset($container_definition['parameters']) ? $container_definition['parameters'] : array();
$this->serviceDefinitions = isset($container_definition['services']) ? $container_definition['services'] : array();
$this->frozen = isset($container_definition['frozen']) ? $container_definition['frozen'] : FALSE;
// Register the service_container with itself.
$this->services['service_container'] = $this;
}
/**
* {@inheritdoc}
*/
protected function createService(array $definition, $id) {
// This method is a verbatim copy of
// \Drupal\Component\DependencyInjection\Container::createService
// except for the following difference:
// - There are no instanceof checks on \stdClass, which are used in the
// parent class to avoid resolving services and parameters when it is
// known from dumping that there is nothing to resolve.
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 = array();
if (isset($definition['arguments'])) {
$arguments = $this->resolveServicesAndParameters($definition['arguments']);
}
if (isset($definition['file'])) {
$file = $this->frozen ? $definition['file'] : current($this->resolveServicesAndParameters(array($definition['file'])));
require_once $file;
}
if (isset($definition['factory'])) {
$factory = $definition['factory'];
if (is_array($factory)) {
$factory = $this->resolveServicesAndParameters(array($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(array($definition['class'])));
$length = isset($definition['arguments_count']) ? $definition['arguments_count'] : count($arguments);
// Optimize class instantiation for services with up to 10 parameters as
// reflection is noticeably slow.
switch ($length) {
case 0:
$service = new $class();
break;
case 1:
$service = new $class($arguments[0]);
break;
case 2:
$service = new $class($arguments[0], $arguments[1]);
break;
case 3:
$service = new $class($arguments[0], $arguments[1], $arguments[2]);
break;
case 4:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3]);
break;
case 5:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4]);
break;
case 6:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5]);
break;
case 7:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]);
break;
case 8:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7]);
break;
case 9:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8]);
break;
case 10:
$service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8], $arguments[9]);
break;
default:
$r = new \ReflectionClass($class);
$service = $r->newInstanceArgs($arguments);
break;
}
}
// Share the service if it is public.
if (!isset($definition['public']) || $definition['public'] !== FALSE) {
// Forward compatibility fix for Symfony 2.8 update.
if (!isset($definition['shared']) || $definition['shared'] !== FALSE) {
$this->services[$id] = $service;
}
}
if (isset($definition['calls'])) {
foreach ($definition['calls'] as $call) {
$method = $call[0];
$arguments = array();
if (!empty($call[1])) {
$arguments = $call[1];
$arguments = $this->resolveServicesAndParameters($arguments);
}
call_user_func_array(array($service, $method), $arguments);
}
}
if (isset($definition['properties'])) {
$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}
*/
protected function resolveServicesAndParameters($arguments) {
// This method is different from the parent method only for the following
// cases:
// - A service is denoted by '@service' and not by a \stdClass object.
// - A parameter is denoted by '%parameter%' and not by a \stdClass object.
// - The depth of the tree representing the arguments is not known in
// advance, so it needs to be fully traversed recursively.
foreach ($arguments as $key => $argument) {
if ($argument instanceof \stdClass) {
$type = $argument->type;
// Private services are a special flavor: In case a private service is
// only used by one other service, the ContainerBuilder uses a
// Definition object as an argument, which does not have an ID set.
// Therefore the format uses a \stdClass object to store the definition
// and to be able to create the service on the fly.
//
// Note: When constructing a private service by hand, 'id' must be set.
//
// The PhpArrayDumper just uses the hash of the private service
// definition to generate a unique ID.
//
// @see \Drupal\Component\DependecyInjection\Dumper\OptimizedPhpArrayDumper::getPrivateServiceCall
if ($type == 'private_service') {
$id = $argument->id;
// Check if the private service already exists - in case it is shared.
if (!empty($argument->shared) && isset($this->privateServices[$id])) {
$arguments[$key] = $this->privateServices[$id];
continue;
}
// Create a private service from a service definition.
$arguments[$key] = $this->createService($argument->value, $id);
if (!empty($argument->shared)) {
$this->privateServices[$id] = $arguments[$key];
}
continue;
}
if ($type !== NULL) {
throw new InvalidArgumentException("Undefined type '$type' while resolving parameters and services.");
}
}
if (is_array($argument)) {
$arguments[$key] = $this->resolveServicesAndParameters($argument);
continue;
}
if (!is_string($argument)) {
continue;
}
// Resolve parameters.
if ($argument[0] === '%') {
$name = substr($argument, 1, -1);
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.
}
$argument = $this->parameters[$name];
$arguments[$key] = $argument;
}
// Resolve services.
if ($argument[0] === '@') {
$id = substr($argument, 1);
$invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
if ($id[0] === '?') {
$id = substr($id, 1);
$invalid_behavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
}
if (isset($this->services[$id])) {
$arguments[$key] = $this->services[$id];
}
else {
$arguments[$key] = $this->get($id, $invalid_behavior);
}
}
}
return $arguments;
}
}

View file

@ -0,0 +1,18 @@
{
"name": "drupal/core-dependency-injection",
"description": "Dependency Injection container optimized for Drupal's needs.",
"keywords": ["drupal", "dependency injection"],
"type": "library",
"homepage": "https://www.drupal.org/project/drupal",
"license": "GPL-2.0+",
"support": {
"issues": "https://www.drupal.org/project/issues/drupal",
"irc": "irc://irc.freenode.net/drupal-contribute",
"source": "https://www.drupal.org/project/drupal/git-instructions"
},
"autoload": {
"psr-4": {
"Drupal\\Component\\DependencyInjection\\": ""
}
}
}