3 namespace Drupal\Component\DependencyInjection\Dumper;
5 use Drupal\Component\Utility\Crypt;
6 use Symfony\Component\DependencyInjection\ContainerInterface;
7 use Symfony\Component\DependencyInjection\Definition;
8 use Symfony\Component\DependencyInjection\Parameter;
9 use Symfony\Component\DependencyInjection\Reference;
10 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
11 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
12 use Symfony\Component\DependencyInjection\Dumper\Dumper;
13 use Symfony\Component\ExpressionLanguage\Expression;
16 * OptimizedPhpArrayDumper dumps a service container as a serialized PHP array.
18 * The format of this dumper is very similar to the internal structure of the
19 * ContainerBuilder, but based on PHP arrays and \stdClass objects instead of
20 * rich value objects for performance reasons.
22 * By removing the abstraction and optimizing some cases like deep collections,
23 * fewer classes need to be loaded, fewer function calls need to be executed and
24 * fewer run time checks need to be made.
26 * In addition to that, this container dumper treats private services as
27 * strictly private with their own private services storage, whereas in the
28 * Symfony service container builder and PHP dumper, shared private services can
29 * still be retrieved via get() from the container.
31 * It is machine-optimized, for a human-readable version based on this one see
32 * \Drupal\Component\DependencyInjection\Dumper\PhpArrayDumper.
34 * @see \Drupal\Component\DependencyInjection\Container
36 class OptimizedPhpArrayDumper extends Dumper {
39 * Whether to serialize service definitions or not.
41 * Service definitions are serialized by default to avoid having to
42 * unserialize the whole container on loading time, which improves early
43 * bootstrap performance for e.g. the page cache.
47 protected $serialize = TRUE;
52 public function dump(array $options = []) {
53 return serialize($this->getArray());
57 * Gets the service container definition as a PHP array.
60 * A PHP array representation of the service container.
62 public function getArray() {
64 $this->aliases = $this->getAliases();
65 $definition['aliases'] = $this->getAliases();
66 $definition['parameters'] = $this->getParameters();
67 $definition['services'] = $this->getServiceDefinitions();
68 $definition['frozen'] = $this->container->isFrozen();
69 $definition['machine_format'] = $this->supportsMachineFormat();
74 * Gets the aliases as a PHP array.
79 protected function getAliases() {
80 $alias_definitions = [];
82 $aliases = $this->container->getAliases();
83 foreach ($aliases as $alias => $id) {
85 while (isset($aliases[$id])) {
86 $id = (string) $aliases[$id];
88 $alias_definitions[$alias] = $id;
91 return $alias_definitions;
95 * Gets parameters of the container as a PHP array.
98 * The escaped and prepared parameters of the container.
100 protected function getParameters() {
101 if (!$this->container->getParameterBag()->all()) {
105 $parameters = $this->container->getParameterBag()->all();
106 $is_frozen = $this->container->isFrozen();
107 return $this->prepareParameters($parameters, $is_frozen);
111 * Gets services of the container as a PHP array.
114 * The service definitions.
116 protected function getServiceDefinitions() {
117 if (!$this->container->getDefinitions()) {
122 foreach ($this->container->getDefinitions() as $id => $definition) {
123 // Only store public service definitions, references to shared private
124 // services are handled in ::getReferenceCall().
125 if ($definition->isPublic()) {
126 $service_definition = $this->getServiceDefinition($definition);
127 $services[$id] = $this->serialize ? serialize($service_definition) : $service_definition;
135 * Prepares parameters for the PHP array dumping.
137 * @param array $parameters
138 * An array of parameters.
139 * @param bool $escape
140 * Whether keys with '%' should be escaped or not.
143 * An array of prepared parameters.
145 protected function prepareParameters(array $parameters, $escape = TRUE) {
147 foreach ($parameters as $key => $value) {
148 if (is_array($value)) {
149 $value = $this->prepareParameters($value, $escape);
151 elseif ($value instanceof Reference) {
152 $value = $this->dumpValue($value);
155 $filtered[$key] = $value;
158 return $escape ? $this->escape($filtered) : $filtered;
162 * Escapes parameters.
164 * @param array $parameters
165 * The parameters to escape for '%' characters.
168 * The escaped parameters.
170 protected function escape(array $parameters) {
173 foreach ($parameters as $key => $value) {
174 if (is_array($value)) {
175 $args[$key] = $this->escape($value);
177 elseif (is_string($value)) {
178 $args[$key] = str_replace('%', '%%', $value);
181 $args[$key] = $value;
189 * Gets a service definition as PHP array.
191 * @param \Symfony\Component\DependencyInjection\Definition $definition
192 * The definition to process.
195 * The service definition as PHP array.
197 * @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
198 * Thrown when the definition is marked as decorated, or with an explicit
199 * scope different from SCOPE_CONTAINER and SCOPE_PROTOTYPE.
201 protected function getServiceDefinition(Definition $definition) {
203 if ($definition->getClass()) {
204 $service['class'] = $definition->getClass();
207 if (!$definition->isPublic()) {
208 $service['public'] = FALSE;
211 if ($definition->getFile()) {
212 $service['file'] = $definition->getFile();
215 if ($definition->isSynthetic()) {
216 $service['synthetic'] = TRUE;
219 if ($definition->isLazy()) {
220 $service['lazy'] = TRUE;
223 if ($definition->getArguments()) {
224 $arguments = $definition->getArguments();
225 $service['arguments'] = $this->dumpCollection($arguments);
226 $service['arguments_count'] = count($arguments);
229 $service['arguments_count'] = 0;
232 if ($definition->getProperties()) {
233 $service['properties'] = $this->dumpCollection($definition->getProperties());
236 if ($definition->getMethodCalls()) {
237 $service['calls'] = $this->dumpMethodCalls($definition->getMethodCalls());
240 if (($scope = $definition->getScope()) !== ContainerInterface::SCOPE_CONTAINER) {
241 if ($scope === ContainerInterface::SCOPE_PROTOTYPE) {
242 // Scope prototype has been replaced with 'shared' => FALSE.
243 // This is a Symfony 2.8 forward compatibility fix.
244 // Reference: https://github.com/symfony/symfony/blob/2.8/UPGRADE-2.8.md#dependencyinjection
245 $service['shared'] = FALSE;
248 throw new InvalidArgumentException("The 'scope' definition is deprecated in Symfony 3.0 and not supported by Drupal 8.");
252 // By default services are shared, so just provide the flag, when needed.
253 if ($definition->isShared() === FALSE) {
254 $service['shared'] = $definition->isShared();
257 if (($decorated = $definition->getDecoratedService()) !== NULL) {
258 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.");
261 if ($callable = $definition->getFactory()) {
262 $service['factory'] = $this->dumpCallable($callable);
265 if ($callable = $definition->getConfigurator()) {
266 $service['configurator'] = $this->dumpCallable($callable);
273 * Dumps method calls to a PHP array.
275 * @param array $calls
276 * An array of method calls.
279 * The PHP array representation of the method calls.
281 protected function dumpMethodCalls(array $calls) {
284 foreach ($calls as $key => $call) {
287 if (!empty($call[1])) {
288 $arguments = $this->dumpCollection($call[1]);
291 $code[$key] = [$method, $arguments];
299 * Dumps a collection to a PHP array.
301 * @param mixed $collection
302 * A collection to process.
303 * @param bool &$resolve
304 * Used for passing the information to the caller whether the given
305 * collection needed to be resolved or not. This is used for optimizing
306 * deep arrays that don't need to be traversed.
308 * @return \stdClass|array
309 * The collection in a suitable format.
311 protected function dumpCollection($collection, &$resolve = FALSE) {
314 foreach ($collection as $key => $value) {
315 if (is_array($value)) {
316 $resolve_collection = FALSE;
317 $code[$key] = $this->dumpCollection($value, $resolve_collection);
319 if ($resolve_collection) {
324 if (is_object($value)) {
327 $code[$key] = $this->dumpValue($value);
336 'type' => 'collection',
338 'resolve' => $resolve,
343 * Dumps callable to a PHP array.
345 * @param array|callable $callable
346 * The callable to process.
349 * The processed callable.
351 protected function dumpCallable($callable) {
352 if (is_array($callable)) {
353 $callable[0] = $this->dumpValue($callable[0]);
354 $callable = [$callable[0], $callable[1]];
361 * Gets a private service definition in a suitable format.
364 * The ID of the service to get a private definition for.
365 * @param \Symfony\Component\DependencyInjection\Definition $definition
366 * The definition to process.
367 * @param bool $shared
368 * (optional) Whether the service will be shared with others.
369 * By default this parameter is FALSE.
372 * A very lightweight private service value object.
374 protected function getPrivateServiceCall($id, Definition $definition, $shared = FALSE) {
375 $service_definition = $this->getServiceDefinition($definition);
377 $hash = Crypt::hashBase64(serialize($service_definition));
378 $id = 'private__' . $hash;
381 'type' => 'private_service',
383 'value' => $service_definition,
389 * Dumps the value to PHP array format.
391 * @param mixed $value
395 * The dumped value in a suitable format.
397 * @throws RuntimeException
398 * When trying to dump object or resource.
400 protected function dumpValue($value) {
401 if (is_array($value)) {
403 foreach ($value as $k => $v) {
404 $code[$k] = $this->dumpValue($v);
409 elseif ($value instanceof Reference) {
410 return $this->getReferenceCall((string) $value, $value);
412 elseif ($value instanceof Definition) {
413 return $this->getPrivateServiceCall(NULL, $value);
415 elseif ($value instanceof Parameter) {
416 return $this->getParameterCall((string) $value);
418 elseif ($value instanceof Expression) {
419 throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
421 elseif (is_object($value)) {
422 // Drupal specific: Instantiated objects have a _serviceId parameter.
423 if (isset($value->_serviceId)) {
424 return $this->getReferenceCall($value->_serviceId);
426 throw new RuntimeException('Unable to dump a service container if a parameter is an object without _serviceId.');
428 elseif (is_resource($value)) {
429 throw new RuntimeException('Unable to dump a service container if a parameter is a resource.');
436 * Gets a service reference for a reference in a suitable PHP array format.
438 * The main difference is that this function treats references to private
439 * services differently and returns a private service reference instead of
440 * a normal reference.
443 * The ID of the service to get a reference for.
444 * @param \Symfony\Component\DependencyInjection\Reference|null $reference
445 * (optional) The reference object to process; needed to get the invalid
448 * @return string|\stdClass
449 * A suitable representation of the service reference.
451 protected function getReferenceCall($id, Reference $reference = NULL) {
452 $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
454 if ($reference !== NULL) {
455 $invalid_behavior = $reference->getInvalidBehavior();
458 // Private shared service.
459 if (isset($this->aliases[$id])) {
460 $id = $this->aliases[$id];
462 $definition = $this->container->getDefinition($id);
463 if (!$definition->isPublic()) {
464 // The ContainerBuilder does not share a private service, but this means a
465 // new service is instantiated every time. Use a private shared service to
466 // circumvent the problem.
467 return $this->getPrivateServiceCall($id, $definition, TRUE);
470 return $this->getServiceCall($id, $invalid_behavior);
474 * Gets a service reference for an ID in a suitable PHP array format.
477 * The ID of the service to get a reference for.
478 * @param int $invalid_behavior
479 * (optional) The invalid behavior of the service.
481 * @return string|\stdClass
482 * A suitable representation of the service reference.
484 protected function getServiceCall($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
488 'invalidBehavior' => $invalid_behavior,
493 * Gets a parameter reference in a suitable PHP array format.
495 * @param string $name
496 * The name of the parameter to get a reference for.
498 * @return string|\stdClass
499 * A suitable representation of the parameter reference.
501 protected function getParameterCall($name) {
503 'type' => 'parameter',
509 * Whether this supports the machine-optimized format or not.
512 * TRUE if this supports machine-optimized format, FALSE otherwise.
514 protected function supportsMachineFormat() {