comparison vendor/symfony/dependency-injection/Dumper/PhpDumper.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 7a779792577d
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\DependencyInjection\Dumper;
13
14 use Symfony\Component\DependencyInjection\Variable;
15 use Symfony\Component\DependencyInjection\Definition;
16 use Symfony\Component\DependencyInjection\ContainerBuilder;
17 use Symfony\Component\DependencyInjection\Container;
18 use Symfony\Component\DependencyInjection\ContainerInterface;
19 use Symfony\Component\DependencyInjection\Reference;
20 use Symfony\Component\DependencyInjection\Parameter;
21 use Symfony\Component\DependencyInjection\Exception\EnvParameterException;
22 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
23 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
24 use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
25 use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper;
26 use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper;
27 use Symfony\Component\DependencyInjection\ExpressionLanguage;
28 use Symfony\Component\ExpressionLanguage\Expression;
29 use Symfony\Component\HttpKernel\Kernel;
30
31 /**
32 * PhpDumper dumps a service container as a PHP class.
33 *
34 * @author Fabien Potencier <fabien@symfony.com>
35 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
36 */
37 class PhpDumper extends Dumper
38 {
39 /**
40 * Characters that might appear in the generated variable name as first character.
41 *
42 * @var string
43 */
44 const FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz';
45
46 /**
47 * Characters that might appear in the generated variable name as any but the first character.
48 *
49 * @var string
50 */
51 const NON_FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_';
52
53 private $inlinedDefinitions;
54 private $definitionVariables;
55 private $referenceVariables;
56 private $variableCount;
57 private $reservedVariables = array('instance', 'class');
58 private $expressionLanguage;
59 private $targetDirRegex;
60 private $targetDirMaxMatches;
61 private $docStar;
62 private $serviceIdToMethodNameMap;
63 private $usedMethodNames;
64
65 /**
66 * @var \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface
67 */
68 private $proxyDumper;
69
70 /**
71 * {@inheritdoc}
72 */
73 public function __construct(ContainerBuilder $container)
74 {
75 parent::__construct($container);
76
77 $this->inlinedDefinitions = new \SplObjectStorage();
78 }
79
80 /**
81 * Sets the dumper to be used when dumping proxies in the generated container.
82 *
83 * @param ProxyDumper $proxyDumper
84 */
85 public function setProxyDumper(ProxyDumper $proxyDumper)
86 {
87 $this->proxyDumper = $proxyDumper;
88 }
89
90 /**
91 * Dumps the service container as a PHP class.
92 *
93 * Available options:
94 *
95 * * class: The class name
96 * * base_class: The base class name
97 * * namespace: The class namespace
98 *
99 * @param array $options An array of options
100 *
101 * @return string A PHP class representing of the service container
102 *
103 * @throws EnvParameterException When an env var exists but has not been dumped
104 */
105 public function dump(array $options = array())
106 {
107 $this->targetDirRegex = null;
108 $options = array_merge(array(
109 'class' => 'ProjectServiceContainer',
110 'base_class' => 'Container',
111 'namespace' => '',
112 'debug' => true,
113 ), $options);
114
115 $this->initializeMethodNamesMap($options['base_class']);
116
117 $this->docStar = $options['debug'] ? '*' : '';
118
119 if (!empty($options['file']) && is_dir($dir = dirname($options['file']))) {
120 // Build a regexp where the first root dirs are mandatory,
121 // but every other sub-dir is optional up to the full path in $dir
122 // Mandate at least 2 root dirs and not more that 5 optional dirs.
123
124 $dir = explode(DIRECTORY_SEPARATOR, realpath($dir));
125 $i = count($dir);
126
127 if (3 <= $i) {
128 $regex = '';
129 $lastOptionalDir = $i > 8 ? $i - 5 : 3;
130 $this->targetDirMaxMatches = $i - $lastOptionalDir;
131
132 while (--$i >= $lastOptionalDir) {
133 $regex = sprintf('(%s%s)?', preg_quote(DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex);
134 }
135
136 do {
137 $regex = preg_quote(DIRECTORY_SEPARATOR.$dir[$i], '#').$regex;
138 } while (0 < --$i);
139
140 $this->targetDirRegex = '#'.preg_quote($dir[0], '#').$regex.'#';
141 }
142 }
143
144 $code = $this->startClass($options['class'], $options['base_class'], $options['namespace']);
145
146 if ($this->container->isFrozen()) {
147 $code .= $this->addFrozenConstructor();
148 $code .= $this->addFrozenCompile();
149 $code .= $this->addIsFrozenMethod();
150 } else {
151 $code .= $this->addConstructor();
152 }
153
154 $code .=
155 $this->addServices().
156 $this->addDefaultParametersMethod().
157 $this->endClass().
158 $this->addProxyClasses()
159 ;
160 $this->targetDirRegex = null;
161
162 $unusedEnvs = array();
163 foreach ($this->container->getEnvCounters() as $env => $use) {
164 if (!$use) {
165 $unusedEnvs[] = $env;
166 }
167 }
168 if ($unusedEnvs) {
169 throw new EnvParameterException($unusedEnvs);
170 }
171
172 return $code;
173 }
174
175 /**
176 * Retrieves the currently set proxy dumper or instantiates one.
177 *
178 * @return ProxyDumper
179 */
180 private function getProxyDumper()
181 {
182 if (!$this->proxyDumper) {
183 $this->proxyDumper = new NullDumper();
184 }
185
186 return $this->proxyDumper;
187 }
188
189 /**
190 * Generates Service local temp variables.
191 *
192 * @param string $cId
193 * @param string $definition
194 *
195 * @return string
196 */
197 private function addServiceLocalTempVariables($cId, $definition)
198 {
199 static $template = " \$%s = %s;\n";
200
201 $localDefinitions = array_merge(
202 array($definition),
203 $this->getInlinedDefinitions($definition)
204 );
205
206 $calls = $behavior = array();
207 foreach ($localDefinitions as $iDefinition) {
208 $this->getServiceCallsFromArguments($iDefinition->getArguments(), $calls, $behavior);
209 $this->getServiceCallsFromArguments($iDefinition->getMethodCalls(), $calls, $behavior);
210 $this->getServiceCallsFromArguments($iDefinition->getProperties(), $calls, $behavior);
211 $this->getServiceCallsFromArguments(array($iDefinition->getConfigurator()), $calls, $behavior);
212 $this->getServiceCallsFromArguments(array($iDefinition->getFactory()), $calls, $behavior);
213 }
214
215 $code = '';
216 foreach ($calls as $id => $callCount) {
217 if ('service_container' === $id || $id === $cId) {
218 continue;
219 }
220
221 if ($callCount > 1) {
222 $name = $this->getNextVariableName();
223 $this->referenceVariables[$id] = new Variable($name);
224
225 if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $behavior[$id]) {
226 $code .= sprintf($template, $name, $this->getServiceCall($id));
227 } else {
228 $code .= sprintf($template, $name, $this->getServiceCall($id, new Reference($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)));
229 }
230 }
231 }
232
233 if ('' !== $code) {
234 $code .= "\n";
235 }
236
237 return $code;
238 }
239
240 /**
241 * Generates code for the proxies to be attached after the container class.
242 *
243 * @return string
244 */
245 private function addProxyClasses()
246 {
247 /* @var $definitions Definition[] */
248 $definitions = array_filter(
249 $this->container->getDefinitions(),
250 array($this->getProxyDumper(), 'isProxyCandidate')
251 );
252 $code = '';
253 $strip = '' === $this->docStar && method_exists('Symfony\Component\HttpKernel\Kernel', 'stripComments');
254
255 foreach ($definitions as $definition) {
256 $proxyCode = "\n".$this->getProxyDumper()->getProxyCode($definition);
257 if ($strip) {
258 $proxyCode = "<?php\n".$proxyCode;
259 $proxyCode = substr(Kernel::stripComments($proxyCode), 5);
260 }
261 $code .= $proxyCode;
262 }
263
264 return $code;
265 }
266
267 /**
268 * Generates the require_once statement for service includes.
269 *
270 * @param string $id The service id
271 * @param Definition $definition
272 *
273 * @return string
274 */
275 private function addServiceInclude($id, $definition)
276 {
277 $template = " require_once %s;\n";
278 $code = '';
279
280 if (null !== $file = $definition->getFile()) {
281 $code .= sprintf($template, $this->dumpValue($file));
282 }
283
284 foreach ($this->getInlinedDefinitions($definition) as $definition) {
285 if (null !== $file = $definition->getFile()) {
286 $code .= sprintf($template, $this->dumpValue($file));
287 }
288 }
289
290 if ('' !== $code) {
291 $code .= "\n";
292 }
293
294 return $code;
295 }
296
297 /**
298 * Generates the inline definition of a service.
299 *
300 * @param string $id
301 * @param Definition $definition
302 *
303 * @return string
304 *
305 * @throws RuntimeException When the factory definition is incomplete
306 * @throws ServiceCircularReferenceException When a circular reference is detected
307 */
308 private function addServiceInlinedDefinitions($id, $definition)
309 {
310 $code = '';
311 $variableMap = $this->definitionVariables;
312 $nbOccurrences = new \SplObjectStorage();
313 $processed = new \SplObjectStorage();
314 $inlinedDefinitions = $this->getInlinedDefinitions($definition);
315
316 foreach ($inlinedDefinitions as $definition) {
317 if (false === $nbOccurrences->contains($definition)) {
318 $nbOccurrences->offsetSet($definition, 1);
319 } else {
320 $i = $nbOccurrences->offsetGet($definition);
321 $nbOccurrences->offsetSet($definition, $i + 1);
322 }
323 }
324
325 foreach ($inlinedDefinitions as $sDefinition) {
326 if ($processed->contains($sDefinition)) {
327 continue;
328 }
329 $processed->offsetSet($sDefinition);
330
331 $class = $this->dumpValue($sDefinition->getClass());
332 if ($nbOccurrences->offsetGet($sDefinition) > 1 || $sDefinition->getMethodCalls() || $sDefinition->getProperties() || null !== $sDefinition->getConfigurator() || false !== strpos($class, '$')) {
333 $name = $this->getNextVariableName();
334 $variableMap->offsetSet($sDefinition, new Variable($name));
335
336 // a construct like:
337 // $a = new ServiceA(ServiceB $b); $b = new ServiceB(ServiceA $a);
338 // this is an indication for a wrong implementation, you can circumvent this problem
339 // by setting up your service structure like this:
340 // $b = new ServiceB();
341 // $a = new ServiceA(ServiceB $b);
342 // $b->setServiceA(ServiceA $a);
343 if ($this->hasReference($id, $sDefinition->getArguments())) {
344 throw new ServiceCircularReferenceException($id, array($id));
345 }
346
347 $code .= $this->addNewInstance($sDefinition, '$'.$name, ' = ', $id);
348
349 if (!$this->hasReference($id, $sDefinition->getMethodCalls(), true) && !$this->hasReference($id, $sDefinition->getProperties(), true)) {
350 $code .= $this->addServiceProperties(null, $sDefinition, $name);
351 $code .= $this->addServiceMethodCalls(null, $sDefinition, $name);
352 $code .= $this->addServiceConfigurator(null, $sDefinition, $name);
353 }
354
355 $code .= "\n";
356 }
357 }
358
359 return $code;
360 }
361
362 /**
363 * Adds the service return statement.
364 *
365 * @param string $id Service id
366 * @param Definition $definition
367 *
368 * @return string
369 */
370 private function addServiceReturn($id, $definition)
371 {
372 if ($this->isSimpleInstance($id, $definition)) {
373 return " }\n";
374 }
375
376 return "\n return \$instance;\n }\n";
377 }
378
379 /**
380 * Generates the service instance.
381 *
382 * @param string $id
383 * @param Definition $definition
384 *
385 * @return string
386 *
387 * @throws InvalidArgumentException
388 * @throws RuntimeException
389 */
390 private function addServiceInstance($id, Definition $definition)
391 {
392 $class = $definition->getClass();
393
394 if ('\\' === substr($class, 0, 1)) {
395 $class = substr($class, 1);
396 }
397
398 $class = $this->dumpValue($class);
399
400 if (0 === strpos($class, "'") && false === strpos($class, '$') && !preg_match('/^\'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) {
401 throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id));
402 }
403
404 $simple = $this->isSimpleInstance($id, $definition);
405 $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition);
406 $instantiation = '';
407
408 if (!$isProxyCandidate && $definition->isShared()) {
409 $instantiation = "\$this->services['$id'] = ".($simple ? '' : '$instance');
410 } elseif (!$simple) {
411 $instantiation = '$instance';
412 }
413
414 $return = '';
415 if ($simple) {
416 $return = 'return ';
417 } else {
418 $instantiation .= ' = ';
419 }
420
421 $code = $this->addNewInstance($definition, $return, $instantiation, $id);
422
423 if (!$simple) {
424 $code .= "\n";
425 }
426
427 return $code;
428 }
429
430 /**
431 * Checks if the definition is a simple instance.
432 *
433 * @param string $id
434 * @param Definition $definition
435 *
436 * @return bool
437 */
438 private function isSimpleInstance($id, Definition $definition)
439 {
440 foreach (array_merge(array($definition), $this->getInlinedDefinitions($definition)) as $sDefinition) {
441 if ($definition !== $sDefinition && !$this->hasReference($id, $sDefinition->getMethodCalls())) {
442 continue;
443 }
444
445 if ($sDefinition->getMethodCalls() || $sDefinition->getProperties() || $sDefinition->getConfigurator()) {
446 return false;
447 }
448 }
449
450 return true;
451 }
452
453 /**
454 * Adds method calls to a service definition.
455 *
456 * @param string $id
457 * @param Definition $definition
458 * @param string $variableName
459 *
460 * @return string
461 */
462 private function addServiceMethodCalls($id, Definition $definition, $variableName = 'instance')
463 {
464 $calls = '';
465 foreach ($definition->getMethodCalls() as $call) {
466 $arguments = array();
467 foreach ($call[1] as $value) {
468 $arguments[] = $this->dumpValue($value);
469 }
470
471 $calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$%s->%s(%s);\n", $variableName, $call[0], implode(', ', $arguments)));
472 }
473
474 return $calls;
475 }
476
477 private function addServiceProperties($id, Definition $definition, $variableName = 'instance')
478 {
479 $code = '';
480 foreach ($definition->getProperties() as $name => $value) {
481 $code .= sprintf(" \$%s->%s = %s;\n", $variableName, $name, $this->dumpValue($value));
482 }
483
484 return $code;
485 }
486
487 /**
488 * Generates the inline definition setup.
489 *
490 * @param string $id
491 * @param Definition $definition
492 *
493 * @return string
494 *
495 * @throws ServiceCircularReferenceException when the container contains a circular reference
496 */
497 private function addServiceInlinedDefinitionsSetup($id, Definition $definition)
498 {
499 $this->referenceVariables[$id] = new Variable('instance');
500
501 $code = '';
502 $processed = new \SplObjectStorage();
503 foreach ($this->getInlinedDefinitions($definition) as $iDefinition) {
504 if ($processed->contains($iDefinition)) {
505 continue;
506 }
507 $processed->offsetSet($iDefinition);
508
509 if (!$this->hasReference($id, $iDefinition->getMethodCalls(), true) && !$this->hasReference($id, $iDefinition->getProperties(), true)) {
510 continue;
511 }
512
513 // if the instance is simple, the return statement has already been generated
514 // so, the only possible way to get there is because of a circular reference
515 if ($this->isSimpleInstance($id, $definition)) {
516 throw new ServiceCircularReferenceException($id, array($id));
517 }
518
519 $name = (string) $this->definitionVariables->offsetGet($iDefinition);
520 $code .= $this->addServiceProperties(null, $iDefinition, $name);
521 $code .= $this->addServiceMethodCalls(null, $iDefinition, $name);
522 $code .= $this->addServiceConfigurator(null, $iDefinition, $name);
523 }
524
525 if ('' !== $code) {
526 $code .= "\n";
527 }
528
529 return $code;
530 }
531
532 /**
533 * Adds configurator definition.
534 *
535 * @param string $id
536 * @param Definition $definition
537 * @param string $variableName
538 *
539 * @return string
540 */
541 private function addServiceConfigurator($id, Definition $definition, $variableName = 'instance')
542 {
543 if (!$callable = $definition->getConfigurator()) {
544 return '';
545 }
546
547 if (is_array($callable)) {
548 if ($callable[0] instanceof Reference
549 || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) {
550 return sprintf(" %s->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
551 }
552
553 $class = $this->dumpValue($callable[0]);
554 // If the class is a string we can optimize call_user_func away
555 if (0 === strpos($class, "'") && false === strpos($class, '$')) {
556 return sprintf(" %s::%s(\$%s);\n", $this->dumpLiteralClass($class), $callable[1], $variableName);
557 }
558
559 if (0 === strpos($class, 'new ')) {
560 return sprintf(" (%s)->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
561 }
562
563 return sprintf(" call_user_func(array(%s, '%s'), \$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
564 }
565
566 return sprintf(" %s(\$%s);\n", $callable, $variableName);
567 }
568
569 /**
570 * Adds a service.
571 *
572 * @param string $id
573 * @param Definition $definition
574 *
575 * @return string
576 */
577 private function addService($id, Definition $definition)
578 {
579 $this->definitionVariables = new \SplObjectStorage();
580 $this->referenceVariables = array();
581 $this->variableCount = 0;
582
583 $return = array();
584
585 if ($definition->isSynthetic()) {
586 $return[] = '@throws RuntimeException always since this service is expected to be injected dynamically';
587 } elseif ($class = $definition->getClass()) {
588 $class = $this->container->resolveEnvPlaceholders($class);
589 $return[] = sprintf('@return %s A %s instance', 0 === strpos($class, '%') ? 'object' : '\\'.ltrim($class, '\\'), ltrim($class, '\\'));
590 } elseif ($definition->getFactory()) {
591 $factory = $definition->getFactory();
592 if (is_string($factory)) {
593 $return[] = sprintf('@return object An instance returned by %s()', $factory);
594 } elseif (is_array($factory) && (is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) {
595 if (is_string($factory[0]) || $factory[0] instanceof Reference) {
596 $return[] = sprintf('@return object An instance returned by %s::%s()', (string) $factory[0], $factory[1]);
597 } elseif ($factory[0] instanceof Definition) {
598 $return[] = sprintf('@return object An instance returned by %s::%s()', $factory[0]->getClass(), $factory[1]);
599 }
600 }
601 }
602
603 if ($definition->isDeprecated()) {
604 if ($return && 0 === strpos($return[count($return) - 1], '@return')) {
605 $return[] = '';
606 }
607
608 $return[] = sprintf('@deprecated %s', $definition->getDeprecationMessage($id));
609 }
610
611 $return = str_replace("\n * \n", "\n *\n", implode("\n * ", $return));
612 $return = $this->container->resolveEnvPlaceholders($return);
613
614 $doc = '';
615 if ($definition->isShared()) {
616 $doc .= <<<'EOF'
617
618 *
619 * This service is shared.
620 * This method always returns the same instance of the service.
621 EOF;
622 }
623
624 if (!$definition->isPublic()) {
625 $doc .= <<<'EOF'
626
627 *
628 * This service is private.
629 * If you want to be able to request this service from the container directly,
630 * make it public, otherwise you might end up with broken code.
631 EOF;
632 }
633
634 if ($definition->isAutowired()) {
635 $doc .= <<<EOF
636
637 *
638 * This service is autowired.
639 EOF;
640 }
641
642 if ($definition->isLazy()) {
643 $lazyInitialization = '$lazyLoad = true';
644 $lazyInitializationDoc = "\n * @param bool \$lazyLoad whether to try lazy-loading the service with a proxy\n *";
645 } else {
646 $lazyInitialization = '';
647 $lazyInitializationDoc = '';
648 }
649
650 // with proxies, for 5.3.3 compatibility, the getter must be public to be accessible to the initializer
651 $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition);
652 $visibility = $isProxyCandidate ? 'public' : 'protected';
653 $methodName = $this->generateMethodName($id);
654 $code = <<<EOF
655
656 /*{$this->docStar}
657 * Gets the '$id' service.$doc
658 *$lazyInitializationDoc
659 * $return
660 */
661 {$visibility} function {$methodName}($lazyInitialization)
662 {
663
664 EOF;
665
666 $code .= $isProxyCandidate ? $this->getProxyDumper()->getProxyFactoryCode($definition, $id, $methodName) : '';
667
668 if ($definition->isSynthetic()) {
669 $code .= sprintf(" throw new RuntimeException('You have requested a synthetic service (\"%s\"). The DIC does not know how to construct this service.');\n }\n", $id);
670 } else {
671 if ($definition->isDeprecated()) {
672 $code .= sprintf(" @trigger_error(%s, E_USER_DEPRECATED);\n\n", $this->export($definition->getDeprecationMessage($id)));
673 }
674
675 $code .=
676 $this->addServiceInclude($id, $definition).
677 $this->addServiceLocalTempVariables($id, $definition).
678 $this->addServiceInlinedDefinitions($id, $definition).
679 $this->addServiceInstance($id, $definition).
680 $this->addServiceInlinedDefinitionsSetup($id, $definition).
681 $this->addServiceProperties($id, $definition).
682 $this->addServiceMethodCalls($id, $definition).
683 $this->addServiceConfigurator($id, $definition).
684 $this->addServiceReturn($id, $definition)
685 ;
686 }
687
688 $this->definitionVariables = null;
689 $this->referenceVariables = null;
690
691 return $code;
692 }
693
694 /**
695 * Adds multiple services.
696 *
697 * @return string
698 */
699 private function addServices()
700 {
701 $publicServices = $privateServices = '';
702 $definitions = $this->container->getDefinitions();
703 ksort($definitions);
704 foreach ($definitions as $id => $definition) {
705 if ($definition->isPublic()) {
706 $publicServices .= $this->addService($id, $definition);
707 } else {
708 $privateServices .= $this->addService($id, $definition);
709 }
710 }
711
712 return $publicServices.$privateServices;
713 }
714
715 private function addNewInstance(Definition $definition, $return, $instantiation, $id)
716 {
717 $class = $this->dumpValue($definition->getClass());
718
719 $arguments = array();
720 foreach ($definition->getArguments() as $value) {
721 $arguments[] = $this->dumpValue($value);
722 }
723
724 if (null !== $definition->getFactory()) {
725 $callable = $definition->getFactory();
726 if (is_array($callable)) {
727 if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $callable[1])) {
728 throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $callable[1] ?: 'n/a'));
729 }
730
731 if ($callable[0] instanceof Reference
732 || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) {
733 return sprintf(" $return{$instantiation}%s->%s(%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : '');
734 }
735
736 $class = $this->dumpValue($callable[0]);
737 // If the class is a string we can optimize call_user_func away
738 if (0 === strpos($class, "'") && false === strpos($class, '$')) {
739 if ("''" === $class) {
740 throw new RuntimeException(sprintf('Cannot dump definition: The "%s" service is defined to be created by a factory but is missing the service reference, did you forget to define the factory service id or class?', $id));
741 }
742
743 return sprintf(" $return{$instantiation}%s::%s(%s);\n", $this->dumpLiteralClass($class), $callable[1], $arguments ? implode(', ', $arguments) : '');
744 }
745
746 if (0 === strpos($class, 'new ')) {
747 return sprintf(" $return{$instantiation}(%s)->%s(%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : '');
748 }
749
750 return sprintf(" $return{$instantiation}call_user_func(array(%s, '%s')%s);\n", $this->dumpValue($callable[0]), $callable[1], $arguments ? ', '.implode(', ', $arguments) : '');
751 }
752
753 return sprintf(" $return{$instantiation}%s(%s);\n", $this->dumpLiteralClass($this->dumpValue($callable)), $arguments ? implode(', ', $arguments) : '');
754 }
755
756 if (false !== strpos($class, '$')) {
757 return sprintf(" \$class = %s;\n\n $return{$instantiation}new \$class(%s);\n", $class, implode(', ', $arguments));
758 }
759
760 return sprintf(" $return{$instantiation}new %s(%s);\n", $this->dumpLiteralClass($class), implode(', ', $arguments));
761 }
762
763 /**
764 * Adds the class headers.
765 *
766 * @param string $class Class name
767 * @param string $baseClass The name of the base class
768 * @param string $namespace The class namespace
769 *
770 * @return string
771 */
772 private function startClass($class, $baseClass, $namespace)
773 {
774 $bagClass = $this->container->isFrozen() ? 'use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;';
775 $namespaceLine = $namespace ? "namespace $namespace;\n" : '';
776
777 return <<<EOF
778 <?php
779 $namespaceLine
780 use Symfony\Component\DependencyInjection\ContainerInterface;
781 use Symfony\Component\DependencyInjection\Container;
782 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
783 use Symfony\Component\DependencyInjection\Exception\LogicException;
784 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
785 $bagClass
786
787 /*{$this->docStar}
788 * $class.
789 *
790 * This class has been auto-generated
791 * by the Symfony Dependency Injection Component.
792 */
793 class $class extends $baseClass
794 {
795 private \$parameters;
796 private \$targetDirs = array();
797
798 EOF;
799 }
800
801 /**
802 * Adds the constructor.
803 *
804 * @return string
805 */
806 private function addConstructor()
807 {
808 $targetDirs = $this->exportTargetDirs();
809 $arguments = $this->container->getParameterBag()->all() ? 'new ParameterBag($this->getDefaultParameters())' : null;
810
811 $code = <<<EOF
812
813 /*{$this->docStar}
814 * Constructor.
815 */
816 public function __construct()
817 {{$targetDirs}
818 parent::__construct($arguments);
819
820 EOF;
821
822 $code .= $this->addMethodMap();
823 $code .= $this->addPrivateServices();
824 $code .= $this->addAliases();
825
826 $code .= <<<'EOF'
827 }
828
829 EOF;
830
831 return $code;
832 }
833
834 /**
835 * Adds the constructor for a frozen container.
836 *
837 * @return string
838 */
839 private function addFrozenConstructor()
840 {
841 $targetDirs = $this->exportTargetDirs();
842
843 $code = <<<EOF
844
845 /*{$this->docStar}
846 * Constructor.
847 */
848 public function __construct()
849 {{$targetDirs}
850 EOF;
851
852 if ($this->container->getParameterBag()->all()) {
853 $code .= "\n \$this->parameters = \$this->getDefaultParameters();\n";
854 }
855
856 $code .= "\n \$this->services = array();\n";
857 $code .= $this->addMethodMap();
858 $code .= $this->addPrivateServices();
859 $code .= $this->addAliases();
860
861 $code .= <<<'EOF'
862 }
863
864 EOF;
865
866 return $code;
867 }
868
869 /**
870 * Adds the constructor for a frozen container.
871 *
872 * @return string
873 */
874 private function addFrozenCompile()
875 {
876 return <<<EOF
877
878 /*{$this->docStar}
879 * {@inheritdoc}
880 */
881 public function compile()
882 {
883 throw new LogicException('You cannot compile a dumped frozen container.');
884 }
885
886 EOF;
887 }
888
889 /**
890 * Adds the isFrozen method for a frozen container.
891 *
892 * @return string
893 */
894 private function addIsFrozenMethod()
895 {
896 return <<<EOF
897
898 /*{$this->docStar}
899 * {@inheritdoc}
900 */
901 public function isFrozen()
902 {
903 return true;
904 }
905
906 EOF;
907 }
908
909 /**
910 * Adds the methodMap property definition.
911 *
912 * @return string
913 */
914 private function addMethodMap()
915 {
916 if (!$definitions = $this->container->getDefinitions()) {
917 return '';
918 }
919
920 $code = " \$this->methodMap = array(\n";
921 ksort($definitions);
922 foreach ($definitions as $id => $definition) {
923 $code .= ' '.$this->export($id).' => '.$this->export($this->generateMethodName($id)).",\n";
924 }
925
926 return $code." );\n";
927 }
928
929 /**
930 * Adds the privates property definition.
931 *
932 * @return string
933 */
934 private function addPrivateServices()
935 {
936 if (!$definitions = $this->container->getDefinitions()) {
937 return '';
938 }
939
940 $code = '';
941 ksort($definitions);
942 foreach ($definitions as $id => $definition) {
943 if (!$definition->isPublic()) {
944 $code .= ' '.$this->export($id)." => true,\n";
945 }
946 }
947
948 if (empty($code)) {
949 return '';
950 }
951
952 $out = " \$this->privates = array(\n";
953 $out .= $code;
954 $out .= " );\n";
955
956 return $out;
957 }
958
959 /**
960 * Adds the aliases property definition.
961 *
962 * @return string
963 */
964 private function addAliases()
965 {
966 if (!$aliases = $this->container->getAliases()) {
967 return $this->container->isFrozen() ? "\n \$this->aliases = array();\n" : '';
968 }
969
970 $code = " \$this->aliases = array(\n";
971 ksort($aliases);
972 foreach ($aliases as $alias => $id) {
973 $id = (string) $id;
974 while (isset($aliases[$id])) {
975 $id = (string) $aliases[$id];
976 }
977 $code .= ' '.$this->export($alias).' => '.$this->export($id).",\n";
978 }
979
980 return $code." );\n";
981 }
982
983 /**
984 * Adds default parameters method.
985 *
986 * @return string
987 */
988 private function addDefaultParametersMethod()
989 {
990 if (!$this->container->getParameterBag()->all()) {
991 return '';
992 }
993
994 $php = array();
995 $dynamicPhp = array();
996
997 foreach ($this->container->getParameterBag()->all() as $key => $value) {
998 if ($key !== $resolvedKey = $this->container->resolveEnvPlaceholders($key)) {
999 throw new InvalidArgumentException(sprintf('Parameter name cannot use env parameters: %s.', $resolvedKey));
1000 }
1001 $export = $this->exportParameters(array($value));
1002 $export = explode('0 => ', substr(rtrim($export, " )\n"), 7, -1), 2);
1003
1004 if (preg_match("/\\\$this->(?:getEnv\('\w++'\)|targetDirs\[\d++\])/", $export[1])) {
1005 $dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;', $export[0], $this->export($key), $export[1]);
1006 } else {
1007 $php[] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]);
1008 }
1009 }
1010 $parameters = sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', 8));
1011
1012 $code = '';
1013 if ($this->container->isFrozen()) {
1014 $code .= <<<'EOF'
1015
1016 /**
1017 * {@inheritdoc}
1018 */
1019 public function getParameter($name)
1020 {
1021 $name = strtolower($name);
1022
1023 if (!(isset($this->parameters[$name]) || array_key_exists($name, $this->parameters) || isset($this->loadedDynamicParameters[$name]))) {
1024 throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
1025 }
1026 if (isset($this->loadedDynamicParameters[$name])) {
1027 return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
1028 }
1029
1030 return $this->parameters[$name];
1031 }
1032
1033 /**
1034 * {@inheritdoc}
1035 */
1036 public function hasParameter($name)
1037 {
1038 $name = strtolower($name);
1039
1040 return isset($this->parameters[$name]) || array_key_exists($name, $this->parameters) || isset($this->loadedDynamicParameters[$name]);
1041 }
1042
1043 /**
1044 * {@inheritdoc}
1045 */
1046 public function setParameter($name, $value)
1047 {
1048 throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
1049 }
1050
1051 /**
1052 * {@inheritdoc}
1053 */
1054 public function getParameterBag()
1055 {
1056 if (null === $this->parameterBag) {
1057 $parameters = $this->parameters;
1058 foreach ($this->loadedDynamicParameters as $name => $loaded) {
1059 $parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
1060 }
1061 $this->parameterBag = new FrozenParameterBag($parameters);
1062 }
1063
1064 return $this->parameterBag;
1065 }
1066
1067 EOF;
1068 if ('' === $this->docStar) {
1069 $code = str_replace('/**', '/*', $code);
1070 }
1071
1072 if ($dynamicPhp) {
1073 $loadedDynamicParameters = $this->exportParameters(array_combine(array_keys($dynamicPhp), array_fill(0, count($dynamicPhp), false)), '', 8);
1074 $getDynamicParameter = <<<'EOF'
1075 switch ($name) {
1076 %s
1077 default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%%s" must be defined.', $name));
1078 }
1079 $this->loadedDynamicParameters[$name] = true;
1080
1081 return $this->dynamicParameters[$name] = $value;
1082 EOF;
1083 $getDynamicParameter = sprintf($getDynamicParameter, implode("\n", $dynamicPhp));
1084 } else {
1085 $loadedDynamicParameters = 'array()';
1086 $getDynamicParameter = str_repeat(' ', 8).'throw new InvalidArgumentException(sprintf(\'The dynamic parameter "%s" must be defined.\', $name));';
1087 }
1088
1089 $code .= <<<EOF
1090
1091 private \$loadedDynamicParameters = {$loadedDynamicParameters};
1092 private \$dynamicParameters = array();
1093
1094 /*{$this->docStar}
1095 * Computes a dynamic parameter.
1096 *
1097 * @param string The name of the dynamic parameter to load
1098 *
1099 * @return mixed The value of the dynamic parameter
1100 *
1101 * @throws InvalidArgumentException When the dynamic parameter does not exist
1102 */
1103 private function getDynamicParameter(\$name)
1104 {
1105 {$getDynamicParameter}
1106 }
1107
1108 EOF;
1109 } elseif ($dynamicPhp) {
1110 throw new RuntimeException('You cannot dump a not-frozen container with dynamic parameters.');
1111 }
1112
1113 $code .= <<<EOF
1114
1115 /*{$this->docStar}
1116 * Gets the default parameters.
1117 *
1118 * @return array An array of the default parameters
1119 */
1120 protected function getDefaultParameters()
1121 {
1122 return $parameters;
1123 }
1124
1125 EOF;
1126
1127 return $code;
1128 }
1129
1130 /**
1131 * Exports parameters.
1132 *
1133 * @param array $parameters
1134 * @param string $path
1135 * @param int $indent
1136 *
1137 * @return string
1138 *
1139 * @throws InvalidArgumentException
1140 */
1141 private function exportParameters(array $parameters, $path = '', $indent = 12)
1142 {
1143 $php = array();
1144 foreach ($parameters as $key => $value) {
1145 if (is_array($value)) {
1146 $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4);
1147 } elseif ($value instanceof Variable) {
1148 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', $value, $path.'/'.$key));
1149 } elseif ($value instanceof Definition) {
1150 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain service definitions. Definition for "%s" found in "%s".', $value->getClass(), $path.'/'.$key));
1151 } elseif ($value instanceof Reference) {
1152 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain references to other services (reference to service "%s" found in "%s").', $value, $path.'/'.$key));
1153 } elseif ($value instanceof Expression) {
1154 throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain expressions. Expression "%s" found in "%s".', $value, $path.'/'.$key));
1155 } else {
1156 $value = $this->export($value);
1157 }
1158
1159 $php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), $this->export($key), $value);
1160 }
1161
1162 return sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', $indent - 4));
1163 }
1164
1165 /**
1166 * Ends the class definition.
1167 *
1168 * @return string
1169 */
1170 private function endClass()
1171 {
1172 return <<<'EOF'
1173 }
1174
1175 EOF;
1176 }
1177
1178 /**
1179 * Wraps the service conditionals.
1180 *
1181 * @param string $value
1182 * @param string $code
1183 *
1184 * @return string
1185 */
1186 private function wrapServiceConditionals($value, $code)
1187 {
1188 if (!$services = ContainerBuilder::getServiceConditionals($value)) {
1189 return $code;
1190 }
1191
1192 $conditions = array();
1193 foreach ($services as $service) {
1194 $conditions[] = sprintf("\$this->has('%s')", $service);
1195 }
1196
1197 // re-indent the wrapped code
1198 $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code)));
1199
1200 return sprintf(" if (%s) {\n%s }\n", implode(' && ', $conditions), $code);
1201 }
1202
1203 /**
1204 * Builds service calls from arguments.
1205 *
1206 * @param array $arguments
1207 * @param array &$calls By reference
1208 * @param array &$behavior By reference
1209 */
1210 private function getServiceCallsFromArguments(array $arguments, array &$calls, array &$behavior)
1211 {
1212 foreach ($arguments as $argument) {
1213 if (is_array($argument)) {
1214 $this->getServiceCallsFromArguments($argument, $calls, $behavior);
1215 } elseif ($argument instanceof Reference) {
1216 $id = (string) $argument;
1217
1218 if (!isset($calls[$id])) {
1219 $calls[$id] = 0;
1220 }
1221 if (!isset($behavior[$id])) {
1222 $behavior[$id] = $argument->getInvalidBehavior();
1223 } elseif (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $behavior[$id]) {
1224 $behavior[$id] = $argument->getInvalidBehavior();
1225 }
1226
1227 ++$calls[$id];
1228 }
1229 }
1230 }
1231
1232 /**
1233 * Returns the inline definition.
1234 *
1235 * @param Definition $definition
1236 *
1237 * @return array
1238 */
1239 private function getInlinedDefinitions(Definition $definition)
1240 {
1241 if (false === $this->inlinedDefinitions->contains($definition)) {
1242 $definitions = array_merge(
1243 $this->getDefinitionsFromArguments($definition->getArguments()),
1244 $this->getDefinitionsFromArguments($definition->getMethodCalls()),
1245 $this->getDefinitionsFromArguments($definition->getProperties()),
1246 $this->getDefinitionsFromArguments(array($definition->getConfigurator())),
1247 $this->getDefinitionsFromArguments(array($definition->getFactory()))
1248 );
1249
1250 $this->inlinedDefinitions->offsetSet($definition, $definitions);
1251
1252 return $definitions;
1253 }
1254
1255 return $this->inlinedDefinitions->offsetGet($definition);
1256 }
1257
1258 /**
1259 * Gets the definition from arguments.
1260 *
1261 * @param array $arguments
1262 *
1263 * @return array
1264 */
1265 private function getDefinitionsFromArguments(array $arguments)
1266 {
1267 $definitions = array();
1268 foreach ($arguments as $argument) {
1269 if (is_array($argument)) {
1270 $definitions = array_merge($definitions, $this->getDefinitionsFromArguments($argument));
1271 } elseif ($argument instanceof Definition) {
1272 $definitions = array_merge(
1273 $definitions,
1274 $this->getInlinedDefinitions($argument),
1275 array($argument)
1276 );
1277 }
1278 }
1279
1280 return $definitions;
1281 }
1282
1283 /**
1284 * Checks if a service id has a reference.
1285 *
1286 * @param string $id
1287 * @param array $arguments
1288 * @param bool $deep
1289 * @param array $visited
1290 *
1291 * @return bool
1292 */
1293 private function hasReference($id, array $arguments, $deep = false, array &$visited = array())
1294 {
1295 foreach ($arguments as $argument) {
1296 if (is_array($argument)) {
1297 if ($this->hasReference($id, $argument, $deep, $visited)) {
1298 return true;
1299 }
1300 } elseif ($argument instanceof Reference) {
1301 $argumentId = (string) $argument;
1302 if ($id === $argumentId) {
1303 return true;
1304 }
1305
1306 if ($deep && !isset($visited[$argumentId]) && 'service_container' !== $argumentId) {
1307 $visited[$argumentId] = true;
1308
1309 $service = $this->container->getDefinition($argumentId);
1310
1311 // if the proxy manager is enabled, disable searching for references in lazy services,
1312 // as these services will be instantiated lazily and don't have direct related references.
1313 if ($service->isLazy() && !$this->getProxyDumper() instanceof NullDumper) {
1314 continue;
1315 }
1316
1317 $arguments = array_merge($service->getMethodCalls(), $service->getArguments(), $service->getProperties());
1318
1319 if ($this->hasReference($id, $arguments, $deep, $visited)) {
1320 return true;
1321 }
1322 }
1323 }
1324 }
1325
1326 return false;
1327 }
1328
1329 /**
1330 * Dumps values.
1331 *
1332 * @param mixed $value
1333 * @param bool $interpolate
1334 *
1335 * @return string
1336 *
1337 * @throws RuntimeException
1338 */
1339 private function dumpValue($value, $interpolate = true)
1340 {
1341 if (is_array($value)) {
1342 $code = array();
1343 foreach ($value as $k => $v) {
1344 $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate));
1345 }
1346
1347 return sprintf('array(%s)', implode(', ', $code));
1348 } elseif ($value instanceof Definition) {
1349 if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) {
1350 return $this->dumpValue($this->definitionVariables->offsetGet($value), $interpolate);
1351 }
1352 if ($value->getMethodCalls()) {
1353 throw new RuntimeException('Cannot dump definitions which have method calls.');
1354 }
1355 if ($value->getProperties()) {
1356 throw new RuntimeException('Cannot dump definitions which have properties.');
1357 }
1358 if (null !== $value->getConfigurator()) {
1359 throw new RuntimeException('Cannot dump definitions which have a configurator.');
1360 }
1361
1362 $arguments = array();
1363 foreach ($value->getArguments() as $argument) {
1364 $arguments[] = $this->dumpValue($argument);
1365 }
1366
1367 if (null !== $value->getFactory()) {
1368 $factory = $value->getFactory();
1369
1370 if (is_string($factory)) {
1371 return sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory)), implode(', ', $arguments));
1372 }
1373
1374 if (is_array($factory)) {
1375 if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $factory[1])) {
1376 throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s)', $factory[1] ?: 'n/a'));
1377 }
1378
1379 if (is_string($factory[0])) {
1380 return sprintf('%s::%s(%s)', $this->dumpLiteralClass($this->dumpValue($factory[0])), $factory[1], implode(', ', $arguments));
1381 }
1382
1383 if ($factory[0] instanceof Definition) {
1384 return sprintf("call_user_func(array(%s, '%s')%s)", $this->dumpValue($factory[0]), $factory[1], count($arguments) > 0 ? ', '.implode(', ', $arguments) : '');
1385 }
1386
1387 if ($factory[0] instanceof Reference) {
1388 return sprintf('%s->%s(%s)', $this->dumpValue($factory[0]), $factory[1], implode(', ', $arguments));
1389 }
1390 }
1391
1392 throw new RuntimeException('Cannot dump definition because of invalid factory');
1393 }
1394
1395 $class = $value->getClass();
1396 if (null === $class) {
1397 throw new RuntimeException('Cannot dump definitions which have no class nor factory.');
1398 }
1399
1400 return sprintf('new %s(%s)', $this->dumpLiteralClass($this->dumpValue($class)), implode(', ', $arguments));
1401 } elseif ($value instanceof Variable) {
1402 return '$'.$value;
1403 } elseif ($value instanceof Reference) {
1404 if (null !== $this->referenceVariables && isset($this->referenceVariables[$id = (string) $value])) {
1405 return $this->dumpValue($this->referenceVariables[$id], $interpolate);
1406 }
1407
1408 return $this->getServiceCall((string) $value, $value);
1409 } elseif ($value instanceof Expression) {
1410 return $this->getExpressionLanguage()->compile((string) $value, array('this' => 'container'));
1411 } elseif ($value instanceof Parameter) {
1412 return $this->dumpParameter($value);
1413 } elseif (true === $interpolate && is_string($value)) {
1414 if (preg_match('/^%([^%]+)%$/', $value, $match)) {
1415 // we do this to deal with non string values (Boolean, integer, ...)
1416 // the preg_replace_callback converts them to strings
1417 return $this->dumpParameter(strtolower($match[1]));
1418 } else {
1419 $replaceParameters = function ($match) {
1420 return "'.".$this->dumpParameter(strtolower($match[2])).".'";
1421 };
1422
1423 $code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, $this->export($value)));
1424
1425 return $code;
1426 }
1427 } elseif (is_object($value) || is_resource($value)) {
1428 throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
1429 }
1430
1431 return $this->export($value);
1432 }
1433
1434 /**
1435 * Dumps a string to a literal (aka PHP Code) class value.
1436 *
1437 * @param string $class
1438 *
1439 * @return string
1440 *
1441 * @throws RuntimeException
1442 */
1443 private function dumpLiteralClass($class)
1444 {
1445 if (false !== strpos($class, '$')) {
1446 return sprintf('${($_ = %s) && false ?: "_"}', $class);
1447 }
1448 if (0 !== strpos($class, "'") || !preg_match('/^\'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(\\\{2}[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*\'$/', $class)) {
1449 throw new RuntimeException(sprintf('Cannot dump definition because of invalid class name (%s)', $class ?: 'n/a'));
1450 }
1451
1452 return '\\'.substr(str_replace('\\\\', '\\', $class), 1, -1);
1453 }
1454
1455 /**
1456 * Dumps a parameter.
1457 *
1458 * @param string $name
1459 *
1460 * @return string
1461 */
1462 private function dumpParameter($name)
1463 {
1464 if ($this->container->isFrozen() && $this->container->hasParameter($name)) {
1465 return $this->dumpValue($this->container->getParameter($name), false);
1466 }
1467
1468 return sprintf("\$this->getParameter('%s')", strtolower($name));
1469 }
1470
1471 /**
1472 * Gets a service call.
1473 *
1474 * @param string $id
1475 * @param Reference $reference
1476 *
1477 * @return string
1478 */
1479 private function getServiceCall($id, Reference $reference = null)
1480 {
1481 if ('service_container' === $id) {
1482 return '$this';
1483 }
1484
1485 if ($this->container->hasDefinition($id) && !$this->container->getDefinition($id)->isPublic()) {
1486 // The following is PHP 5.5 syntax for what could be written as "(\$this->services['$id'] ?? \$this->{$this->generateMethodName($id)}())" on PHP>=7.0
1487
1488 return "\${(\$_ = isset(\$this->services['$id']) ? \$this->services['$id'] : \$this->{$this->generateMethodName($id)}()) && false ?: '_'}";
1489 }
1490 if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) {
1491 return sprintf('$this->get(\'%s\', ContainerInterface::NULL_ON_INVALID_REFERENCE)', $id);
1492 }
1493
1494 if ($this->container->hasAlias($id)) {
1495 $id = (string) $this->container->getAlias($id);
1496 }
1497
1498 return sprintf('$this->get(\'%s\')', $id);
1499 }
1500
1501 /**
1502 * Initializes the method names map to avoid conflicts with the Container methods.
1503 *
1504 * @param string $class the container base class
1505 */
1506 private function initializeMethodNamesMap($class)
1507 {
1508 $this->serviceIdToMethodNameMap = array();
1509 $this->usedMethodNames = array();
1510
1511 try {
1512 $reflectionClass = new \ReflectionClass($class);
1513 foreach ($reflectionClass->getMethods() as $method) {
1514 $this->usedMethodNames[strtolower($method->getName())] = true;
1515 }
1516 } catch (\ReflectionException $e) {
1517 }
1518 }
1519
1520 /**
1521 * Convert a service id to a valid PHP method name.
1522 *
1523 * @param string $id
1524 *
1525 * @return string
1526 *
1527 * @throws InvalidArgumentException
1528 */
1529 private function generateMethodName($id)
1530 {
1531 if (isset($this->serviceIdToMethodNameMap[$id])) {
1532 return $this->serviceIdToMethodNameMap[$id];
1533 }
1534
1535 $name = Container::camelize($id);
1536 $name = preg_replace('/[^a-zA-Z0-9_\x7f-\xff]/', '', $name);
1537 $methodName = 'get'.$name.'Service';
1538 $suffix = 1;
1539
1540 while (isset($this->usedMethodNames[strtolower($methodName)])) {
1541 ++$suffix;
1542 $methodName = 'get'.$name.$suffix.'Service';
1543 }
1544
1545 $this->serviceIdToMethodNameMap[$id] = $methodName;
1546 $this->usedMethodNames[strtolower($methodName)] = true;
1547
1548 return $methodName;
1549 }
1550
1551 /**
1552 * Returns the next name to use.
1553 *
1554 * @return string
1555 */
1556 private function getNextVariableName()
1557 {
1558 $firstChars = self::FIRST_CHARS;
1559 $firstCharsLength = strlen($firstChars);
1560 $nonFirstChars = self::NON_FIRST_CHARS;
1561 $nonFirstCharsLength = strlen($nonFirstChars);
1562
1563 while (true) {
1564 $name = '';
1565 $i = $this->variableCount;
1566
1567 if ('' === $name) {
1568 $name .= $firstChars[$i % $firstCharsLength];
1569 $i = (int) ($i / $firstCharsLength);
1570 }
1571
1572 while ($i > 0) {
1573 --$i;
1574 $name .= $nonFirstChars[$i % $nonFirstCharsLength];
1575 $i = (int) ($i / $nonFirstCharsLength);
1576 }
1577
1578 ++$this->variableCount;
1579
1580 // check that the name is not reserved
1581 if (in_array($name, $this->reservedVariables, true)) {
1582 continue;
1583 }
1584
1585 return $name;
1586 }
1587 }
1588
1589 private function getExpressionLanguage()
1590 {
1591 if (null === $this->expressionLanguage) {
1592 if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
1593 throw new RuntimeException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
1594 }
1595 $providers = $this->container->getExpressionLanguageProviders();
1596 $this->expressionLanguage = new ExpressionLanguage(null, $providers);
1597
1598 if ($this->container->isTrackingResources()) {
1599 foreach ($providers as $provider) {
1600 $this->container->addObjectResource($provider);
1601 }
1602 }
1603 }
1604
1605 return $this->expressionLanguage;
1606 }
1607
1608 private function exportTargetDirs()
1609 {
1610 return null === $this->targetDirRegex ? '' : <<<EOF
1611
1612 \$dir = __DIR__;
1613 for (\$i = 1; \$i <= {$this->targetDirMaxMatches}; ++\$i) {
1614 \$this->targetDirs[\$i] = \$dir = dirname(\$dir);
1615 }
1616 EOF;
1617 }
1618
1619 private function export($value)
1620 {
1621 if (null !== $this->targetDirRegex && is_string($value) && preg_match($this->targetDirRegex, $value, $matches, PREG_OFFSET_CAPTURE)) {
1622 $prefix = $matches[0][1] ? $this->doExport(substr($value, 0, $matches[0][1])).'.' : '';
1623 $suffix = $matches[0][1] + strlen($matches[0][0]);
1624 $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix)) : '';
1625 $dirname = '__DIR__';
1626
1627 if (0 < $offset = 1 + $this->targetDirMaxMatches - count($matches)) {
1628 $dirname = sprintf('$this->targetDirs[%d]', $offset);
1629 }
1630
1631 if ($prefix || $suffix) {
1632 return sprintf('(%s%s%s)', $prefix, $dirname, $suffix);
1633 }
1634
1635 return $dirname;
1636 }
1637
1638 return $this->doExport($value);
1639 }
1640
1641 private function doExport($value)
1642 {
1643 $export = var_export($value, true);
1644
1645 if ("'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('%s').'")) {
1646 $export = $resolvedExport;
1647 if ("'" === $export[1]) {
1648 $export = substr($export, 3);
1649 }
1650 if (".''" === substr($export, -3)) {
1651 $export = substr($export, 0, -3);
1652 }
1653 }
1654
1655 return $export;
1656 }
1657 }