PhpArrayContainer.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. <?php
  2. namespace Drupal\Component\DependencyInjection;
  3. use Symfony\Component\DependencyInjection\ContainerInterface;
  4. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  5. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  6. /**
  7. * Provides a container optimized for Drupal's needs.
  8. *
  9. * This container implementation is compatible with the default Symfony
  10. * dependency injection container and similar to the Symfony ContainerBuilder
  11. * class, but optimized for speed.
  12. *
  13. * It is based on a human-readable PHP array container definition with a
  14. * structure very similar to the YAML container definition.
  15. *
  16. * @see \Drupal\Component\DependencyInjection\Container
  17. * @see \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper
  18. * @see \Drupal\Component\DependencyInjection\DependencySerializationTrait
  19. *
  20. * @ingroup container
  21. */
  22. class PhpArrayContainer extends Container {
  23. /**
  24. * {@inheritdoc}
  25. */
  26. public function __construct(array $container_definition = []) {
  27. if (isset($container_definition['machine_format']) && $container_definition['machine_format'] === TRUE) {
  28. 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.');
  29. }
  30. // Do not call the parent's constructor as it would bail on the
  31. // machine-optimized format.
  32. $this->aliases = isset($container_definition['aliases']) ? $container_definition['aliases'] : [];
  33. $this->parameters = isset($container_definition['parameters']) ? $container_definition['parameters'] : [];
  34. $this->serviceDefinitions = isset($container_definition['services']) ? $container_definition['services'] : [];
  35. $this->frozen = isset($container_definition['frozen']) ? $container_definition['frozen'] : FALSE;
  36. // Register the service_container with itself.
  37. $this->services['service_container'] = $this;
  38. }
  39. /**
  40. * {@inheritdoc}
  41. */
  42. protected function createService(array $definition, $id) {
  43. // This method is a verbatim copy of
  44. // \Drupal\Component\DependencyInjection\Container::createService
  45. // except for the following difference:
  46. // - There are no instanceof checks on \stdClass, which are used in the
  47. // parent class to avoid resolving services and parameters when it is
  48. // known from dumping that there is nothing to resolve.
  49. if (isset($definition['synthetic']) && $definition['synthetic'] === TRUE) {
  50. 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));
  51. }
  52. $arguments = [];
  53. if (isset($definition['arguments'])) {
  54. $arguments = $this->resolveServicesAndParameters($definition['arguments']);
  55. }
  56. if (isset($definition['file'])) {
  57. $file = $this->frozen ? $definition['file'] : current($this->resolveServicesAndParameters([$definition['file']]));
  58. require_once $file;
  59. }
  60. if (isset($definition['factory'])) {
  61. $factory = $definition['factory'];
  62. if (is_array($factory)) {
  63. $factory = $this->resolveServicesAndParameters([$factory[0], $factory[1]]);
  64. }
  65. elseif (!is_string($factory)) {
  66. throw new RuntimeException(sprintf('Cannot create service "%s" because of invalid factory', $id));
  67. }
  68. $service = call_user_func_array($factory, $arguments);
  69. }
  70. else {
  71. $class = $this->frozen ? $definition['class'] : current($this->resolveServicesAndParameters([$definition['class']]));
  72. $length = isset($definition['arguments_count']) ? $definition['arguments_count'] : count($arguments);
  73. // Optimize class instantiation for services with up to 10 parameters as
  74. // reflection is noticeably slow.
  75. switch ($length) {
  76. case 0:
  77. $service = new $class();
  78. break;
  79. case 1:
  80. $service = new $class($arguments[0]);
  81. break;
  82. case 2:
  83. $service = new $class($arguments[0], $arguments[1]);
  84. break;
  85. case 3:
  86. $service = new $class($arguments[0], $arguments[1], $arguments[2]);
  87. break;
  88. case 4:
  89. $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3]);
  90. break;
  91. case 5:
  92. $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4]);
  93. break;
  94. case 6:
  95. $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5]);
  96. break;
  97. case 7:
  98. $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6]);
  99. break;
  100. case 8:
  101. $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7]);
  102. break;
  103. case 9:
  104. $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8]);
  105. break;
  106. case 10:
  107. $service = new $class($arguments[0], $arguments[1], $arguments[2], $arguments[3], $arguments[4], $arguments[5], $arguments[6], $arguments[7], $arguments[8], $arguments[9]);
  108. break;
  109. default:
  110. $r = new \ReflectionClass($class);
  111. $service = $r->newInstanceArgs($arguments);
  112. break;
  113. }
  114. }
  115. if (!isset($definition['shared']) || $definition['shared'] !== FALSE) {
  116. $this->services[$id] = $service;
  117. }
  118. if (isset($definition['calls'])) {
  119. foreach ($definition['calls'] as $call) {
  120. $method = $call[0];
  121. $arguments = [];
  122. if (!empty($call[1])) {
  123. $arguments = $call[1];
  124. $arguments = $this->resolveServicesAndParameters($arguments);
  125. }
  126. call_user_func_array([$service, $method], $arguments);
  127. }
  128. }
  129. if (isset($definition['properties'])) {
  130. $definition['properties'] = $this->resolveServicesAndParameters($definition['properties']);
  131. foreach ($definition['properties'] as $key => $value) {
  132. $service->{$key} = $value;
  133. }
  134. }
  135. if (isset($definition['configurator'])) {
  136. $callable = $definition['configurator'];
  137. if (is_array($callable)) {
  138. $callable = $this->resolveServicesAndParameters($callable);
  139. }
  140. if (!is_callable($callable)) {
  141. throw new InvalidArgumentException(sprintf('The configurator for class "%s" is not a callable.', get_class($service)));
  142. }
  143. call_user_func($callable, $service);
  144. }
  145. return $service;
  146. }
  147. /**
  148. * {@inheritdoc}
  149. */
  150. protected function resolveServicesAndParameters($arguments) {
  151. // This method is different from the parent method only for the following
  152. // cases:
  153. // - A service is denoted by '@service' and not by a \stdClass object.
  154. // - A parameter is denoted by '%parameter%' and not by a \stdClass object.
  155. // - The depth of the tree representing the arguments is not known in
  156. // advance, so it needs to be fully traversed recursively.
  157. foreach ($arguments as $key => $argument) {
  158. if ($argument instanceof \stdClass) {
  159. $type = $argument->type;
  160. // Private services are a special flavor: In case a private service is
  161. // only used by one other service, the ContainerBuilder uses a
  162. // Definition object as an argument, which does not have an ID set.
  163. // Therefore the format uses a \stdClass object to store the definition
  164. // and to be able to create the service on the fly.
  165. //
  166. // Note: When constructing a private service by hand, 'id' must be set.
  167. //
  168. // The PhpArrayDumper just uses the hash of the private service
  169. // definition to generate a unique ID.
  170. //
  171. // @see \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper::getPrivateServiceCall
  172. if ($type == 'private_service') {
  173. $id = $argument->id;
  174. // Check if the private service already exists - in case it is shared.
  175. if (!empty($argument->shared) && isset($this->privateServices[$id])) {
  176. $arguments[$key] = $this->privateServices[$id];
  177. continue;
  178. }
  179. // Create a private service from a service definition.
  180. $arguments[$key] = $this->createService($argument->value, $id);
  181. if (!empty($argument->shared)) {
  182. $this->privateServices[$id] = $arguments[$key];
  183. }
  184. continue;
  185. }
  186. if ($type !== NULL) {
  187. throw new InvalidArgumentException("Undefined type '$type' while resolving parameters and services.");
  188. }
  189. }
  190. if (is_array($argument)) {
  191. $arguments[$key] = $this->resolveServicesAndParameters($argument);
  192. continue;
  193. }
  194. if (!is_string($argument)) {
  195. continue;
  196. }
  197. // Resolve parameters.
  198. if ($argument[0] === '%') {
  199. $name = substr($argument, 1, -1);
  200. if (!isset($this->parameters[$name])) {
  201. $arguments[$key] = $this->getParameter($name);
  202. // This can never be reached as getParameter() throws an Exception,
  203. // because we already checked that the parameter is not set above.
  204. }
  205. $argument = $this->parameters[$name];
  206. $arguments[$key] = $argument;
  207. }
  208. // Resolve services.
  209. if ($argument[0] === '@') {
  210. $id = substr($argument, 1);
  211. $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  212. if ($id[0] === '?') {
  213. $id = substr($id, 1);
  214. $invalid_behavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  215. }
  216. if (isset($this->services[$id])) {
  217. $arguments[$key] = $this->services[$id];
  218. }
  219. else {
  220. $arguments[$key] = $this->get($id, $invalid_behavior);
  221. }
  222. }
  223. }
  224. return $arguments;
  225. }
  226. }