PhpDumper.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\DependencyInjection\Dumper;
  11. use Symfony\Component\DependencyInjection\Exception\CircularReferenceException;
  12. use Symfony\Component\DependencyInjection\Variable;
  13. use Symfony\Component\DependencyInjection\Definition;
  14. use Symfony\Component\DependencyInjection\ContainerBuilder;
  15. use Symfony\Component\DependencyInjection\Container;
  16. use Symfony\Component\DependencyInjection\ContainerInterface;
  17. use Symfony\Component\DependencyInjection\Reference;
  18. use Symfony\Component\DependencyInjection\Parameter;
  19. /**
  20. * PhpDumper dumps a service container as a PHP class.
  21. *
  22. * @author Fabien Potencier <fabien@symfony.com>
  23. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  24. */
  25. class PhpDumper extends Dumper
  26. {
  27. /**
  28. * Characters that might appear in the generated variable name as first character
  29. * @var string
  30. */
  31. const FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz';
  32. /**
  33. * Characters that might appear in the generated variable name as any but the first character
  34. * @var string
  35. */
  36. const NON_FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_';
  37. private $inlinedDefinitions;
  38. private $definitionVariables;
  39. private $referenceVariables;
  40. private $variableCount;
  41. private $reservedVariables = array('instance', 'class');
  42. /**
  43. * {@inheritDoc}
  44. */
  45. public function __construct(ContainerBuilder $container)
  46. {
  47. parent::__construct($container);
  48. $this->inlinedDefinitions = new \SplObjectStorage;
  49. }
  50. /**
  51. * Dumps the service container as a PHP class.
  52. *
  53. * Available options:
  54. *
  55. * * class: The class name
  56. * * base_class: The base class name
  57. *
  58. * @param array $options An array of options
  59. *
  60. * @return string A PHP class representing of the service container
  61. */
  62. public function dump(array $options = array())
  63. {
  64. $options = array_merge(array(
  65. 'class' => 'ProjectServiceContainer',
  66. 'base_class' => 'Container',
  67. ), $options);
  68. $code = $this->startClass($options['class'], $options['base_class']);
  69. if ($this->container->isFrozen()) {
  70. $code .= $this->addFrozenConstructor();
  71. } else {
  72. $code .= $this->addConstructor();
  73. }
  74. $code .=
  75. $this->addServices().
  76. $this->addDefaultParametersMethod().
  77. $this->endClass()
  78. ;
  79. return $code;
  80. }
  81. /**
  82. * Generates Service local temp variables.
  83. *
  84. * @param string $cId
  85. * @param string $definition
  86. * @return string
  87. */
  88. private function addServiceLocalTempVariables($cId, $definition)
  89. {
  90. static $template = " \$%s = %s;\n";
  91. $localDefinitions = array_merge(
  92. array($definition),
  93. $this->getInlinedDefinitions($definition)
  94. );
  95. $calls = $behavior = array();
  96. foreach ($localDefinitions as $iDefinition) {
  97. $this->getServiceCallsFromArguments($iDefinition->getArguments(), $calls, $behavior);
  98. $this->getServiceCallsFromArguments($iDefinition->getMethodCalls(), $calls, $behavior);
  99. $this->getServiceCallsFromArguments($iDefinition->getProperties(), $calls, $behavior);
  100. }
  101. $code = '';
  102. foreach ($calls as $id => $callCount) {
  103. if ('service_container' === $id || $id === $cId) {
  104. continue;
  105. }
  106. if ($callCount > 1) {
  107. $name = $this->getNextVariableName();
  108. $this->referenceVariables[$id] = new Variable($name);
  109. if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE === $behavior[$id]) {
  110. $code .= sprintf($template, $name, $this->getServiceCall($id));
  111. } else {
  112. $code .= sprintf($template, $name, $this->getServiceCall($id, new Reference($id, ContainerInterface::NULL_ON_INVALID_REFERENCE)));
  113. }
  114. }
  115. }
  116. if ('' !== $code) {
  117. $code .= "\n";
  118. }
  119. return $code;
  120. }
  121. /**
  122. * Generates the require_once statement for service includes.
  123. *
  124. * @param string $id The service id
  125. * @param Definition $definition
  126. * @return string
  127. */
  128. private function addServiceInclude($id, $definition)
  129. {
  130. $template = " require_once %s;\n";
  131. $code = '';
  132. if (null !== $file = $definition->getFile()) {
  133. $code .= sprintf($template, $this->dumpValue($file));
  134. }
  135. foreach ($this->getInlinedDefinitions($definition) as $definition) {
  136. if (null !== $file = $definition->getFile()) {
  137. $code .= sprintf($template, $this->dumpValue($file));
  138. }
  139. }
  140. if ('' !== $code) {
  141. $code .= "\n";
  142. }
  143. return $code;
  144. }
  145. /**
  146. * Generates the inline definition of a service.
  147. *
  148. * @param string $id
  149. * @param Definition $definition
  150. * @return string
  151. */
  152. private function addServiceInlinedDefinitions($id, $definition)
  153. {
  154. $code = '';
  155. $variableMap = $this->definitionVariables;
  156. $nbOccurrences = new \SplObjectStorage();
  157. $processed = new \SplObjectStorage();
  158. $inlinedDefinitions = $this->getInlinedDefinitions($definition);
  159. foreach ($inlinedDefinitions as $definition) {
  160. if (false === $nbOccurrences->contains($definition)) {
  161. $nbOccurrences->offsetSet($definition, 1);
  162. } else {
  163. $i = $nbOccurrences->offsetGet($definition);
  164. $nbOccurrences->offsetSet($definition, $i+1);
  165. }
  166. }
  167. foreach ($inlinedDefinitions as $sDefinition) {
  168. if ($processed->contains($sDefinition)) {
  169. continue;
  170. }
  171. $processed->offsetSet($sDefinition);
  172. $class = $this->dumpValue($sDefinition->getClass());
  173. if ($nbOccurrences->offsetGet($sDefinition) > 1 || count($sDefinition->getMethodCalls()) > 0 || $sDefinition->getProperties() || null !== $sDefinition->getConfigurator() || false !== strpos($class, '$')) {
  174. $name = $this->getNextVariableName();
  175. $variableMap->offsetSet($sDefinition, new Variable($name));
  176. // a construct like:
  177. // $a = new ServiceA(ServiceB $b); $b = new ServiceB(ServiceA $a);
  178. // this is an indication for a wrong implementation, you can circumvent this problem
  179. // by setting up your service structure like this:
  180. // $b = new ServiceB();
  181. // $a = new ServiceA(ServiceB $b);
  182. // $b->setServiceA(ServiceA $a);
  183. if ($this->hasReference($id, $sDefinition->getArguments())) {
  184. throw new CircularReferenceException($id, array($id));
  185. }
  186. $arguments = array();
  187. foreach ($sDefinition->getArguments() as $argument) {
  188. $arguments[] = $this->dumpValue($argument);
  189. }
  190. if (null !== $sDefinition->getFactoryMethod()) {
  191. if (null !== $sDefinition->getFactoryClass()) {
  192. $code .= sprintf(" \$%s = call_user_func(array(%s, '%s')%s);\n", $name, $this->dumpValue($sDefinition->getFactoryClass()), $sDefinition->getFactoryMethod(), count($arguments) > 0 ? ', '.implode(', ', $arguments) : '');
  193. } elseif (null !== $sDefinition->getFactoryService()) {
  194. $code .= sprintf(" \$%s = %s->%s(%s);\n", $name, $this->getServiceCall($sDefinition->getFactoryService()), $sDefinition->getFactoryMethod(), implode(', ', $arguments));
  195. } else {
  196. throw new \RuntimeException('Factory service or factory class must be defined in service definition for '.$id);
  197. }
  198. } elseif (false !== strpos($class, '$')) {
  199. $code .= sprintf(" \$class = %s;\n \$%s = new \$class(%s);\n", $class, $name, implode(', ', $arguments));
  200. } else {
  201. $code .= sprintf(" \$%s = new \\%s(%s);\n", $name, substr(str_replace('\\\\', '\\', $class), 1, -1), implode(', ', $arguments));
  202. }
  203. if (!$this->hasReference($id, $sDefinition->getMethodCalls()) && !$this->hasReference($id, $sDefinition->getProperties())) {
  204. $code .= $this->addServiceMethodCalls(null, $sDefinition, $name);
  205. $code .= $this->addServiceProperties(null, $sDefinition, $name);
  206. $code .= $this->addServiceConfigurator(null, $sDefinition, $name);
  207. }
  208. $code .= "\n";
  209. }
  210. }
  211. return $code;
  212. }
  213. /**
  214. * Adds the service return statement.
  215. *
  216. * @param string $id Service id
  217. * @param Definition $definition
  218. * @return string
  219. */
  220. private function addServiceReturn($id, $definition)
  221. {
  222. if ($this->isSimpleInstance($id, $definition)) {
  223. return " }\n";
  224. }
  225. return "\n return \$instance;\n }\n";
  226. }
  227. /**
  228. * Generates the service instance.
  229. *
  230. * @param string $id
  231. * @param Definition $definition
  232. * @return string
  233. *
  234. * @throws \InvalidArgumentException
  235. * @throws \RuntimeException
  236. */
  237. private function addServiceInstance($id, $definition)
  238. {
  239. $class = $this->dumpValue($definition->getClass());
  240. 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)) {
  241. throw new \InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id));
  242. }
  243. $arguments = array();
  244. foreach ($definition->getArguments() as $value) {
  245. $arguments[] = $this->dumpValue($value);
  246. }
  247. $simple = $this->isSimpleInstance($id, $definition);
  248. $instantiation = '';
  249. if (ContainerInterface::SCOPE_CONTAINER === $definition->getScope()) {
  250. $instantiation = "\$this->services['$id'] = ".($simple ? '' : '$instance');
  251. } else if (ContainerInterface::SCOPE_PROTOTYPE !== $scope = $definition->getScope()) {
  252. $instantiation = "\$this->services['$id'] = \$this->scopedServices['$scope']['$id'] = ".($simple ? '' : '$instance');
  253. } elseif (!$simple) {
  254. $instantiation = '$instance';
  255. }
  256. $return = '';
  257. if ($simple) {
  258. $return = 'return ';
  259. } else {
  260. $instantiation .= ' = ';
  261. }
  262. if (null !== $definition->getFactoryMethod()) {
  263. if (null !== $definition->getFactoryClass()) {
  264. $code = sprintf(" $return{$instantiation}call_user_func(array(%s, '%s')%s);\n", $this->dumpValue($definition->getFactoryClass()), $definition->getFactoryMethod(), $arguments ? ', '.implode(', ', $arguments) : '');
  265. } elseif (null !== $definition->getFactoryService()) {
  266. $code = sprintf(" $return{$instantiation}%s->%s(%s);\n", $this->getServiceCall($definition->getFactoryService()), $definition->getFactoryMethod(), implode(', ', $arguments));
  267. } else {
  268. throw new \RuntimeException('Factory method requires a factory service or factory class in service definition for '.$id);
  269. }
  270. } elseif (false !== strpos($class, '$')) {
  271. $code = sprintf(" \$class = %s;\n $return{$instantiation}new \$class(%s);\n", $class, implode(', ', $arguments));
  272. } else {
  273. $code = sprintf(" $return{$instantiation}new \\%s(%s);\n", substr(str_replace('\\\\', '\\', $class), 1, -1), implode(', ', $arguments));
  274. }
  275. if (!$simple) {
  276. $code .= "\n";
  277. }
  278. return $code;
  279. }
  280. /**
  281. * Checks if the definition is a simple instance.
  282. *
  283. * @param string $id
  284. * @param Definition $definition
  285. * @return Boolean
  286. */
  287. private function isSimpleInstance($id, $definition)
  288. {
  289. foreach (array_merge(array($definition), $this->getInlinedDefinitions($definition)) as $sDefinition) {
  290. if ($definition !== $sDefinition && !$this->hasReference($id, $sDefinition->getMethodCalls())) {
  291. continue;
  292. }
  293. if ($sDefinition->getMethodCalls() || $sDefinition->getProperties() || $sDefinition->getConfigurator()) {
  294. return false;
  295. }
  296. }
  297. return true;
  298. }
  299. /**
  300. * Adds method calls to a service definition.
  301. *
  302. * @param string $id
  303. * @param Definition $definition
  304. * @param string $variableName
  305. * @return string
  306. */
  307. private function addServiceMethodCalls($id, $definition, $variableName = 'instance')
  308. {
  309. $calls = '';
  310. foreach ($definition->getMethodCalls() as $call) {
  311. $arguments = array();
  312. foreach ($call[1] as $value) {
  313. $arguments[] = $this->dumpValue($value);
  314. }
  315. $calls .= $this->wrapServiceConditionals($call[1], sprintf(" \$%s->%s(%s);\n", $variableName, $call[0], implode(', ', $arguments)));
  316. }
  317. return $calls;
  318. }
  319. private function addServiceProperties($id, $definition, $variableName = 'instance')
  320. {
  321. $code = '';
  322. foreach ($definition->getProperties() as $name => $value) {
  323. $code .= sprintf(" \$%s = new \ReflectionProperty(\$%s, %s);\n", $refName = $this->getNextVariableName(), $variableName, var_export($name, true));
  324. $code .= sprintf(" \$%s->setAccessible(true);\n", $refName);
  325. $code .= sprintf(" \$%s->setValue(\$%s, %s);\n", $refName, $variableName, $this->dumpValue($value));
  326. }
  327. return $code;
  328. }
  329. /**
  330. * Generates the inline definition setup.
  331. *
  332. * @param string $id
  333. * @param Definition $definition
  334. * @return string
  335. */
  336. private function addServiceInlinedDefinitionsSetup($id, $definition)
  337. {
  338. $this->referenceVariables[$id] = new Variable('instance');
  339. $code = '';
  340. $processed = new \SplObjectStorage();
  341. foreach ($this->getInlinedDefinitions($definition) as $iDefinition) {
  342. if ($processed->contains($iDefinition)) {
  343. continue;
  344. }
  345. $processed->offsetSet($iDefinition);
  346. if (!$this->hasReference($id, $iDefinition->getMethodCalls())) {
  347. continue;
  348. }
  349. if ($iDefinition->getMethodCalls()) {
  350. $code .= $this->addServiceMethodCalls(null, $iDefinition, (string) $this->definitionVariables->offsetGet($iDefinition));
  351. }
  352. if ($iDefinition->getConfigurator()) {
  353. $code .= $this->addServiceConfigurator(null, $iDefinition, (string) $this->definitionVariables->offsetGet($iDefinition));
  354. }
  355. }
  356. if ('' !== $code) {
  357. $code .= "\n";
  358. }
  359. return $code;
  360. }
  361. /**
  362. * Adds configurator definition
  363. *
  364. * @param string $id
  365. * @param Definition $definition
  366. * @param string $variableName
  367. * @return string
  368. */
  369. private function addServiceConfigurator($id, $definition, $variableName = 'instance')
  370. {
  371. if (!$callable = $definition->getConfigurator()) {
  372. return '';
  373. }
  374. if (is_array($callable)) {
  375. if (is_object($callable[0]) && $callable[0] instanceof Reference) {
  376. return sprintf(" %s->%s(\$%s);\n", $this->getServiceCall((string) $callable[0]), $callable[1], $variableName);
  377. }
  378. return sprintf(" call_user_func(array(%s, '%s'), \$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
  379. }
  380. return sprintf(" %s(\$%s);\n", $callable, $variableName);
  381. }
  382. /**
  383. * Adds a service
  384. *
  385. * @param string $id
  386. * @param Definition $definition
  387. * @return string
  388. */
  389. private function addService($id, $definition)
  390. {
  391. $name = Container::camelize($id);
  392. $this->definitionVariables = new \SplObjectStorage();
  393. $this->referenceVariables = array();
  394. $this->variableCount = 0;
  395. $return = '';
  396. if ($definition->isSynthetic()) {
  397. $return = sprintf('@throws \RuntimeException always since this service is expected to be injected dynamically');
  398. } elseif ($class = $definition->getClass()) {
  399. $return = sprintf("@return %s A %s instance.", 0 === strpos($class, '%') ? 'Object' : $class, $class);
  400. } elseif ($definition->getFactoryClass()) {
  401. $return = sprintf('@return Object An instance returned by %s::%s().', $definition->getFactoryClass(), $definition->getFactoryMethod());
  402. } elseif ($definition->getFactoryService()) {
  403. $return = sprintf('@return Object An instance returned by %s::%s().', $definition->getFactoryService(), $definition->getFactoryMethod());
  404. }
  405. $doc = '';
  406. if (ContainerInterface::SCOPE_PROTOTYPE !== $definition->getScope()) {
  407. $doc .= <<<EOF
  408. *
  409. * This service is shared.
  410. * This method always returns the same instance of the service.
  411. EOF;
  412. }
  413. if (!$definition->isPublic()) {
  414. $doc .= <<<EOF
  415. *
  416. * This service is private.
  417. * If you want to be able to request this service from the container directly,
  418. * make it public, otherwise you might end up with broken code.
  419. EOF;
  420. }
  421. $code = <<<EOF
  422. /**
  423. * Gets the '$id' service.$doc
  424. *
  425. * $return
  426. */
  427. protected function get{$name}Service()
  428. {
  429. EOF;
  430. $scope = $definition->getScope();
  431. if (ContainerInterface::SCOPE_CONTAINER !== $scope && ContainerInterface::SCOPE_PROTOTYPE !== $scope) {
  432. $code .= <<<EOF
  433. if (!isset(\$this->scopedServices['$scope'])) {
  434. throw new InactiveScopeException('$id', '$scope');
  435. }
  436. EOF;
  437. }
  438. if ($definition->isSynthetic()) {
  439. $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);
  440. } else {
  441. $code .=
  442. $this->addServiceInclude($id, $definition).
  443. $this->addServiceLocalTempVariables($id, $definition).
  444. $this->addServiceInlinedDefinitions($id, $definition).
  445. $this->addServiceInstance($id, $definition).
  446. $this->addServiceInlinedDefinitionsSetup($id, $definition).
  447. $this->addServiceMethodCalls($id, $definition).
  448. $this->addServiceProperties($id, $definition).
  449. $this->addServiceConfigurator($id, $definition).
  450. $this->addServiceReturn($id, $definition)
  451. ;
  452. }
  453. $this->definitionVariables = null;
  454. $this->referenceVariables = null;
  455. return $code;
  456. }
  457. /**
  458. * Adds a service alias.
  459. *
  460. * @param string $alias
  461. * @param string $id
  462. * @return string
  463. */
  464. private function addServiceAlias($alias, $id)
  465. {
  466. $name = Container::camelize($alias);
  467. $type = 'Object';
  468. if ($this->container->hasDefinition($id)) {
  469. $class = $this->container->getDefinition($id)->getClass();
  470. $type = 0 === strpos($class, '%') ? 'Object' : $class;
  471. }
  472. return <<<EOF
  473. /**
  474. * Gets the $alias service alias.
  475. *
  476. * @return $type An instance of the $id service
  477. */
  478. protected function get{$name}Service()
  479. {
  480. return {$this->getServiceCall($id)};
  481. }
  482. EOF;
  483. }
  484. /**
  485. * Adds multiple services
  486. *
  487. * @return string
  488. */
  489. private function addServices()
  490. {
  491. $publicServices = $privateServices = $aliasServices = '';
  492. $definitions = $this->container->getDefinitions();
  493. ksort($definitions);
  494. foreach ($definitions as $id => $definition) {
  495. if ($definition->isPublic()) {
  496. $publicServices .= $this->addService($id, $definition);
  497. } else {
  498. $privateServices .= $this->addService($id, $definition);
  499. }
  500. }
  501. $aliases = $this->container->getAliases();
  502. ksort($aliases);
  503. foreach ($aliases as $alias => $id) {
  504. $aliasServices .= $this->addServiceAlias($alias, $id);
  505. }
  506. return $publicServices.$aliasServices.$privateServices;
  507. }
  508. /**
  509. * Adds the class headers.
  510. *
  511. * @param string $class Class name
  512. * @param string $baseClass The name of the base class
  513. * @return string
  514. */
  515. private function startClass($class, $baseClass)
  516. {
  517. $bagClass = $this->container->isFrozen() ? '' : 'use Symfony\Component\DependencyInjection\ParameterBag\\ParameterBag;';
  518. return <<<EOF
  519. <?php
  520. use Symfony\Component\DependencyInjection\ContainerInterface;
  521. use Symfony\Component\DependencyInjection\Container;
  522. use Symfony\Component\DependencyInjection\Exception\InactiveScopeException;
  523. use Symfony\Component\DependencyInjection\Reference;
  524. use Symfony\Component\DependencyInjection\Parameter;
  525. $bagClass
  526. /**
  527. * $class
  528. *
  529. * This class has been auto-generated
  530. * by the Symfony Dependency Injection Component.
  531. */
  532. class $class extends $baseClass
  533. {
  534. EOF;
  535. }
  536. /**
  537. * Adds the constructor.
  538. *
  539. * @return string
  540. */
  541. private function addConstructor()
  542. {
  543. $code = <<<EOF
  544. /**
  545. * Constructor.
  546. */
  547. public function __construct()
  548. {
  549. parent::__construct(new ParameterBag(\$this->getDefaultParameters()));
  550. EOF;
  551. if (count($scopes = $this->container->getScopes()) > 0) {
  552. $code .= "\n";
  553. $code .= " \$this->scopes = ".$this->dumpValue($scopes).";\n";
  554. $code .= " \$this->scopeChildren = ".$this->dumpValue($this->container->getScopeChildren()).";\n";
  555. }
  556. $code .= <<<EOF
  557. }
  558. EOF;
  559. return $code;
  560. }
  561. /**
  562. * Adds the constructor for a frozen container.
  563. *
  564. * @return string
  565. */
  566. private function addFrozenConstructor()
  567. {
  568. $code = <<<EOF
  569. /**
  570. * Constructor.
  571. */
  572. public function __construct()
  573. {
  574. \$this->parameters = \$this->getDefaultParameters();
  575. \$this->services =
  576. \$this->scopedServices =
  577. \$this->scopeStacks = array();
  578. \$this->set('service_container', \$this);
  579. EOF;
  580. $code .= "\n";
  581. if (count($scopes = $this->container->getScopes()) > 0) {
  582. $code .= " \$this->scopes = ".$this->dumpValue($scopes).";\n";
  583. $code .= " \$this->scopeChildren = ".$this->dumpValue($this->container->getScopeChildren()).";\n";
  584. } else {
  585. $code .= " \$this->scopes = array();\n";
  586. $code .= " \$this->scopeChildren = array();\n";
  587. }
  588. $code .= <<<EOF
  589. }
  590. EOF;
  591. return $code;
  592. }
  593. /**
  594. * Adds default parameters method.
  595. *
  596. * @return string
  597. */
  598. private function addDefaultParametersMethod()
  599. {
  600. if (!$this->container->getParameterBag()->all()) {
  601. return '';
  602. }
  603. $parameters = $this->exportParameters($this->container->getParameterBag()->all());
  604. $code = '';
  605. if ($this->container->isFrozen()) {
  606. $code .= <<<EOF
  607. /**
  608. * {@inheritdoc}
  609. */
  610. public function getParameter(\$name)
  611. {
  612. \$name = strtolower(\$name);
  613. if (!array_key_exists(\$name, \$this->parameters)) {
  614. throw new \InvalidArgumentException(sprintf('The parameter "%s" must be defined.', \$name));
  615. }
  616. return \$this->parameters[\$name];
  617. }
  618. /**
  619. * {@inheritdoc}
  620. */
  621. public function hasParameter(\$name)
  622. {
  623. return array_key_exists(strtolower(\$name), \$this->parameters);
  624. }
  625. /**
  626. * {@inheritdoc}
  627. */
  628. public function setParameter(\$name, \$value)
  629. {
  630. throw new \LogicException('Impossible to call set() on a frozen ParameterBag.');
  631. }
  632. EOF;
  633. }
  634. $code .= <<<EOF
  635. /**
  636. * Gets the default parameters.
  637. *
  638. * @return array An array of the default parameters
  639. */
  640. protected function getDefaultParameters()
  641. {
  642. return $parameters;
  643. }
  644. EOF;
  645. return $code;
  646. }
  647. /**
  648. * Exports parameters.
  649. *
  650. * @param array $parameters
  651. * @param string $path
  652. * @param integer $indent
  653. * @return string
  654. */
  655. private function exportParameters($parameters, $path = '', $indent = 12)
  656. {
  657. $php = array();
  658. foreach ($parameters as $key => $value) {
  659. if (is_array($value)) {
  660. $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4);
  661. } elseif ($value instanceof Variable) {
  662. throw new \InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', $value, $path.'/'.$key));
  663. } elseif ($value instanceof Definition) {
  664. 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));
  665. } elseif ($value instanceof Reference) {
  666. 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));
  667. } else {
  668. $value = var_export($value, true);
  669. }
  670. $php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), var_export($key, true), $value);
  671. }
  672. return sprintf("array(\n%s\n%s)", implode("\n", $php), str_repeat(' ', $indent - 4));
  673. }
  674. /**
  675. * Ends the class definition.
  676. *
  677. * @return void
  678. */
  679. private function endClass()
  680. {
  681. return <<<EOF
  682. }
  683. EOF;
  684. }
  685. /**
  686. * Wraps the service conditionals.
  687. *
  688. * @param string $value
  689. * @param string $code
  690. * @return string
  691. */
  692. private function wrapServiceConditionals($value, $code)
  693. {
  694. if (!$services = ContainerBuilder::getServiceConditionals($value)) {
  695. return $code;
  696. }
  697. $conditions = array();
  698. foreach ($services as $service) {
  699. $conditions[] = sprintf("\$this->has('%s')", $service);
  700. }
  701. // re-indent the wrapped code
  702. $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code)));
  703. return sprintf(" if (%s) {\n%s }\n", implode(' && ', $conditions), $code);
  704. }
  705. /**
  706. * Builds service calls from arguments
  707. *
  708. * @param array $arguments
  709. * @param string $calls By reference
  710. * @param string $behavior By reference
  711. * @return void
  712. */
  713. private function getServiceCallsFromArguments(array $arguments, array &$calls, array &$behavior)
  714. {
  715. foreach ($arguments as $argument) {
  716. if (is_array($argument)) {
  717. $this->getServiceCallsFromArguments($argument, $calls, $behavior);
  718. } else if ($argument instanceof Reference) {
  719. $id = (string) $argument;
  720. if (!isset($calls[$id])) {
  721. $calls[$id] = 0;
  722. }
  723. if (!isset($behavior[$id])) {
  724. $behavior[$id] = $argument->getInvalidBehavior();
  725. } else if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $behavior[$id]) {
  726. $behavior[$id] = $argument->getInvalidBehavior();
  727. }
  728. $calls[$id] += 1;
  729. }
  730. }
  731. }
  732. /**
  733. * Returns the inline definition
  734. *
  735. * @param Definition $definition
  736. * @return array
  737. */
  738. private function getInlinedDefinitions(Definition $definition)
  739. {
  740. if (false === $this->inlinedDefinitions->contains($definition)) {
  741. $definitions = array_merge(
  742. $this->getDefinitionsFromArguments($definition->getArguments()),
  743. $this->getDefinitionsFromArguments($definition->getMethodCalls()),
  744. $this->getDefinitionsFromArguments($definition->getProperties())
  745. );
  746. $this->inlinedDefinitions->offsetSet($definition, $definitions);
  747. return $definitions;
  748. }
  749. return $this->inlinedDefinitions->offsetGet($definition);
  750. }
  751. /**
  752. * Gets the definition from arguments
  753. *
  754. * @param array $arguments
  755. * @return array
  756. */
  757. private function getDefinitionsFromArguments(array $arguments)
  758. {
  759. $definitions = array();
  760. foreach ($arguments as $argument) {
  761. if (is_array($argument)) {
  762. $definitions = array_merge($definitions, $this->getDefinitionsFromArguments($argument));
  763. } else if ($argument instanceof Definition) {
  764. $definitions = array_merge(
  765. $definitions,
  766. $this->getInlinedDefinitions($argument),
  767. array($argument)
  768. );
  769. }
  770. }
  771. return $definitions;
  772. }
  773. /**
  774. * Checks if a service id has a reference
  775. *
  776. * @param string $id
  777. * @param array $arguments
  778. * @return Boolean
  779. */
  780. private function hasReference($id, array $arguments)
  781. {
  782. foreach ($arguments as $argument) {
  783. if (is_array($argument)) {
  784. if ($this->hasReference($id, $argument)) {
  785. return true;
  786. }
  787. } else if ($argument instanceof Reference) {
  788. if ($id === (string) $argument) {
  789. return true;
  790. }
  791. }
  792. }
  793. return false;
  794. }
  795. /**
  796. * Dumps values.
  797. *
  798. * @param array $value
  799. * @param Boolean $interpolate
  800. * @return string
  801. */
  802. private function dumpValue($value, $interpolate = true)
  803. {
  804. if (is_array($value)) {
  805. $code = array();
  806. foreach ($value as $k => $v) {
  807. $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate));
  808. }
  809. return sprintf('array(%s)', implode(', ', $code));
  810. } elseif (is_object($value) && $value instanceof Definition) {
  811. if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) {
  812. return $this->dumpValue($this->definitionVariables->offsetGet($value), $interpolate);
  813. }
  814. if (count($value->getMethodCalls()) > 0) {
  815. throw new \RuntimeException('Cannot dump definitions which have method calls.');
  816. }
  817. if (null !== $value->getConfigurator()) {
  818. throw new \RuntimeException('Cannot dump definitions which have a configurator.');
  819. }
  820. $arguments = array();
  821. foreach ($value->getArguments() as $argument) {
  822. $arguments[] = $this->dumpValue($argument);
  823. }
  824. $class = $this->dumpValue($value->getClass());
  825. if (false !== strpos($class, '$')) {
  826. throw new \RuntimeException('Cannot dump definitions which have a variable class name.');
  827. }
  828. if (null !== $value->getFactoryMethod()) {
  829. if (null !== $value->getFactoryClass()) {
  830. return sprintf("call_user_func(array(%s, '%s')%s)", $this->dumpValue($value->getFactoryClass()), $value->getFactoryMethod(), count($arguments) > 0 ? ', '.implode(', ', $arguments) : '');
  831. } elseif (null !== $value->getFactoryService()) {
  832. return sprintf("%s->%s(%s)", $this->getServiceCall($value->getFactoryService()), $value->getFactoryMethod(), implode(', ', $arguments));
  833. } else {
  834. throw new \RuntimeException('Cannot dump definitions which have factory method without factory service or factory class.');
  835. }
  836. }
  837. return sprintf("new \\%s(%s)", substr(str_replace('\\\\', '\\', $class), 1, -1), implode(', ', $arguments));
  838. } elseif (is_object($value) && $value instanceof Variable) {
  839. return '$'.$value;
  840. } elseif (is_object($value) && $value instanceof Reference) {
  841. if (null !== $this->referenceVariables && isset($this->referenceVariables[$id = (string) $value])) {
  842. return $this->dumpValue($this->referenceVariables[$id], $interpolate);
  843. }
  844. return $this->getServiceCall((string) $value, $value);
  845. } elseif (is_object($value) && $value instanceof Parameter) {
  846. return $this->dumpParameter($value);
  847. } elseif (true === $interpolate && is_string($value)) {
  848. if (preg_match('/^%([^%]+)%$/', $value, $match)) {
  849. // we do this to deal with non string values (Boolean, integer, ...)
  850. // the preg_replace_callback converts them to strings
  851. return $this->dumpParameter(strtolower($match[1]));
  852. } else {
  853. $that = $this;
  854. $replaceParameters = function ($match) use ($that)
  855. {
  856. return sprintf("'.".$that->dumpParameter(strtolower($match[2])).".'");
  857. };
  858. $code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, var_export($value, true)));
  859. // optimize string
  860. $code = preg_replace(array("/^''\./", "/\.''$/", "/'\.'/", "/\.''\./"), array('', '', '', '.'), $code);
  861. return $code;
  862. }
  863. } elseif (is_object($value) || is_resource($value)) {
  864. throw new \RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
  865. } else {
  866. return var_export($value, true);
  867. }
  868. }
  869. /**
  870. * Dumps a parameter
  871. *
  872. * @param string $name
  873. * @return string
  874. */
  875. public function dumpParameter($name)
  876. {
  877. if ($this->container->isFrozen() && $this->container->hasParameter($name)) {
  878. return $this->dumpValue($this->container->getParameter($name), false);
  879. }
  880. return sprintf("\$this->getParameter('%s')", strtolower($name));
  881. }
  882. /**
  883. * Gets a service call
  884. *
  885. * @param string $id
  886. * @param Reference $reference
  887. * @return string
  888. */
  889. private function getServiceCall($id, Reference $reference = null)
  890. {
  891. if ('service_container' === $id) {
  892. return '$this';
  893. }
  894. if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $reference->getInvalidBehavior()) {
  895. return sprintf('$this->get(\'%s\', ContainerInterface::NULL_ON_INVALID_REFERENCE)', $id);
  896. } else {
  897. if ($this->container->hasAlias($id)) {
  898. $id = (string) $this->container->getAlias($id);
  899. }
  900. return sprintf('$this->get(\'%s\')', $id);
  901. }
  902. }
  903. /**
  904. * Returns the next name to use
  905. *
  906. * @return string
  907. */
  908. private function getNextVariableName()
  909. {
  910. $firstChars = self::FIRST_CHARS;
  911. $firstCharsLength = strlen($firstChars);
  912. $nonFirstChars = self::NON_FIRST_CHARS;
  913. $nonFirstCharsLength = strlen($nonFirstChars);
  914. while (true) {
  915. $name = '';
  916. $i = $this->variableCount;
  917. if ('' === $name) {
  918. $name .= $firstChars[$i%$firstCharsLength];
  919. $i = intval($i/$firstCharsLength);
  920. }
  921. while ($i > 0) {
  922. $i -= 1;
  923. $name .= $nonFirstChars[$i%$nonFirstCharsLength];
  924. $i = intval($i/$nonFirstCharsLength);
  925. }
  926. $this->variableCount += 1;
  927. // check that the name is not reserved
  928. if (in_array($name, $this->reservedVariables, true)) {
  929. continue;
  930. }
  931. return $name;
  932. }
  933. }
  934. }