annotate vendor/symfony/dependency-injection/Dumper/PhpDumper.php @ 13:5fb285c0d0e3

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