PhpDumper.php 60 KB

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