PhpDumper.php 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246
  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 Composer\Autoload\ClassLoader;
  12. use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader;
  13. use Symfony\Component\DependencyInjection\Argument\AbstractArgument;
  14. use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
  15. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  16. use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
  17. use Symfony\Component\DependencyInjection\Argument\ServiceLocator;
  18. use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
  19. use Symfony\Component\DependencyInjection\Compiler\AnalyzeServiceReferencesPass;
  20. use Symfony\Component\DependencyInjection\Compiler\CheckCircularReferencesPass;
  21. use Symfony\Component\DependencyInjection\Compiler\ServiceReferenceGraphNode;
  22. use Symfony\Component\DependencyInjection\Container;
  23. use Symfony\Component\DependencyInjection\ContainerBuilder;
  24. use Symfony\Component\DependencyInjection\ContainerInterface;
  25. use Symfony\Component\DependencyInjection\Definition;
  26. use Symfony\Component\DependencyInjection\Exception\EnvParameterException;
  27. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  28. use Symfony\Component\DependencyInjection\Exception\LogicException;
  29. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  30. use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
  31. use Symfony\Component\DependencyInjection\ExpressionLanguage;
  32. use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\DumperInterface as ProxyDumper;
  33. use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper;
  34. use Symfony\Component\DependencyInjection\Loader\FileLoader;
  35. use Symfony\Component\DependencyInjection\Parameter;
  36. use Symfony\Component\DependencyInjection\Reference;
  37. use Symfony\Component\DependencyInjection\ServiceLocator as BaseServiceLocator;
  38. use Symfony\Component\DependencyInjection\TypedReference;
  39. use Symfony\Component\DependencyInjection\Variable;
  40. use Symfony\Component\ErrorHandler\DebugClassLoader;
  41. use Symfony\Component\ExpressionLanguage\Expression;
  42. use Symfony\Component\HttpKernel\Kernel;
  43. /**
  44. * PhpDumper dumps a service container as a PHP class.
  45. *
  46. * @author Fabien Potencier <fabien@symfony.com>
  47. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  48. */
  49. class PhpDumper extends Dumper
  50. {
  51. /**
  52. * Characters that might appear in the generated variable name as first character.
  53. */
  54. public const FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz';
  55. /**
  56. * Characters that might appear in the generated variable name as any but the first character.
  57. */
  58. public const NON_FIRST_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789_';
  59. private $definitionVariables;
  60. private $referenceVariables;
  61. private $variableCount;
  62. private $inlinedDefinitions;
  63. private $serviceCalls;
  64. private $reservedVariables = ['instance', 'class', 'this', 'container'];
  65. private $expressionLanguage;
  66. private $targetDirRegex;
  67. private $targetDirMaxMatches;
  68. private $docStar;
  69. private $serviceIdToMethodNameMap;
  70. private $usedMethodNames;
  71. private $namespace;
  72. private $asFiles;
  73. private $hotPathTag;
  74. private $preloadTags;
  75. private $inlineFactories;
  76. private $inlineRequires;
  77. private $inlinedRequires = [];
  78. private $circularReferences = [];
  79. private $singleUsePrivateIds = [];
  80. private $preload = [];
  81. private $addThrow = false;
  82. private $addGetService = false;
  83. private $locatedIds = [];
  84. private $serviceLocatorTag;
  85. private $exportedVariables = [];
  86. private $baseClass;
  87. /**
  88. * @var ProxyDumper
  89. */
  90. private $proxyDumper;
  91. /**
  92. * {@inheritdoc}
  93. */
  94. public function __construct(ContainerBuilder $container)
  95. {
  96. if (!$container->isCompiled()) {
  97. throw new LogicException('Cannot dump an uncompiled container.');
  98. }
  99. parent::__construct($container);
  100. }
  101. /**
  102. * Sets the dumper to be used when dumping proxies in the generated container.
  103. */
  104. public function setProxyDumper(ProxyDumper $proxyDumper)
  105. {
  106. $this->proxyDumper = $proxyDumper;
  107. }
  108. /**
  109. * Dumps the service container as a PHP class.
  110. *
  111. * Available options:
  112. *
  113. * * class: The class name
  114. * * base_class: The base class name
  115. * * namespace: The class namespace
  116. * * as_files: To split the container in several files
  117. *
  118. * @return string|array A PHP class representing the service container or an array of PHP files if the "as_files" option is set
  119. *
  120. * @throws EnvParameterException When an env var exists but has not been dumped
  121. */
  122. public function dump(array $options = [])
  123. {
  124. $this->locatedIds = [];
  125. $this->targetDirRegex = null;
  126. $this->inlinedRequires = [];
  127. $this->exportedVariables = [];
  128. $options = array_merge([
  129. 'class' => 'ProjectServiceContainer',
  130. 'base_class' => 'Container',
  131. 'namespace' => '',
  132. 'as_files' => false,
  133. 'debug' => true,
  134. 'hot_path_tag' => 'container.hot_path',
  135. 'preload_tags' => ['container.preload', 'container.no_preload'],
  136. 'inline_factories_parameter' => 'container.dumper.inline_factories',
  137. 'inline_class_loader_parameter' => 'container.dumper.inline_class_loader',
  138. 'preload_classes' => [],
  139. 'service_locator_tag' => 'container.service_locator',
  140. 'build_time' => time(),
  141. ], $options);
  142. $this->addThrow = $this->addGetService = false;
  143. $this->namespace = $options['namespace'];
  144. $this->asFiles = $options['as_files'];
  145. $this->hotPathTag = $options['hot_path_tag'];
  146. $this->preloadTags = $options['preload_tags'];
  147. $this->inlineFactories = $this->asFiles && $options['inline_factories_parameter'] && $this->container->hasParameter($options['inline_factories_parameter']) && $this->container->getParameter($options['inline_factories_parameter']);
  148. $this->inlineRequires = $options['inline_class_loader_parameter'] && ($this->container->hasParameter($options['inline_class_loader_parameter']) ? $this->container->getParameter($options['inline_class_loader_parameter']) : (\PHP_VERSION_ID < 70400 || $options['debug']));
  149. $this->serviceLocatorTag = $options['service_locator_tag'];
  150. if (0 !== strpos($baseClass = $options['base_class'], '\\') && 'Container' !== $baseClass) {
  151. $baseClass = sprintf('%s\%s', $options['namespace'] ? '\\'.$options['namespace'] : '', $baseClass);
  152. $this->baseClass = $baseClass;
  153. } elseif ('Container' === $baseClass) {
  154. $this->baseClass = Container::class;
  155. } else {
  156. $this->baseClass = $baseClass;
  157. }
  158. $this->initializeMethodNamesMap('Container' === $baseClass ? Container::class : $baseClass);
  159. if ($this->getProxyDumper() instanceof NullDumper) {
  160. (new AnalyzeServiceReferencesPass(true, false))->process($this->container);
  161. try {
  162. (new CheckCircularReferencesPass())->process($this->container);
  163. } catch (ServiceCircularReferenceException $e) {
  164. $path = $e->getPath();
  165. end($path);
  166. $path[key($path)] .= '". Try running "composer require symfony/proxy-manager-bridge';
  167. throw new ServiceCircularReferenceException($e->getServiceId(), $path);
  168. }
  169. }
  170. $this->analyzeReferences();
  171. $this->docStar = $options['debug'] ? '*' : '';
  172. if (!empty($options['file']) && is_dir($dir = \dirname($options['file']))) {
  173. // Build a regexp where the first root dirs are mandatory,
  174. // but every other sub-dir is optional up to the full path in $dir
  175. // Mandate at least 1 root dir and not more than 5 optional dirs.
  176. $dir = explode(\DIRECTORY_SEPARATOR, realpath($dir));
  177. $i = \count($dir);
  178. if (2 + (int) ('\\' === \DIRECTORY_SEPARATOR) <= $i) {
  179. $regex = '';
  180. $lastOptionalDir = $i > 8 ? $i - 5 : (2 + (int) ('\\' === \DIRECTORY_SEPARATOR));
  181. $this->targetDirMaxMatches = $i - $lastOptionalDir;
  182. while (--$i >= $lastOptionalDir) {
  183. $regex = sprintf('(%s%s)?', preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#'), $regex);
  184. }
  185. do {
  186. $regex = preg_quote(\DIRECTORY_SEPARATOR.$dir[$i], '#').$regex;
  187. } while (0 < --$i);
  188. $this->targetDirRegex = '#(^|file://|[:;, \|\r\n])'.preg_quote($dir[0], '#').$regex.'#';
  189. }
  190. }
  191. $proxyClasses = $this->inlineFactories ? $this->generateProxyClasses() : null;
  192. if ($options['preload_classes']) {
  193. $this->preload = array_combine($options['preload_classes'], $options['preload_classes']);
  194. }
  195. $code =
  196. $this->startClass($options['class'], $baseClass).
  197. $this->addServices($services).
  198. $this->addDeprecatedAliases().
  199. $this->addDefaultParametersMethod()
  200. ;
  201. $proxyClasses = $proxyClasses ?? $this->generateProxyClasses();
  202. if ($this->addGetService) {
  203. $code = preg_replace(
  204. "/(\r?\n\r?\n public function __construct.+?\\{\r?\n)/s",
  205. "\n protected \$getService;$1 \$this->getService = \\Closure::fromCallable([\$this, 'getService']);\n",
  206. $code,
  207. 1
  208. );
  209. }
  210. if ($this->asFiles) {
  211. $fileTemplate = <<<EOF
  212. <?php
  213. use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
  214. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  215. /*{$this->docStar}
  216. * @internal This class has been auto-generated by the Symfony Dependency Injection Component.
  217. */
  218. class %s extends {$options['class']}
  219. {%s}
  220. EOF;
  221. $files = [];
  222. $preloadedFiles = [];
  223. $ids = $this->container->getRemovedIds();
  224. foreach ($this->container->getDefinitions() as $id => $definition) {
  225. if (!$definition->isPublic()) {
  226. $ids[$id] = true;
  227. }
  228. }
  229. if ($ids = array_keys($ids)) {
  230. sort($ids);
  231. $c = "<?php\n\nreturn [\n";
  232. foreach ($ids as $id) {
  233. $c .= ' '.$this->doExport($id)." => true,\n";
  234. }
  235. $files['removed-ids.php'] = $c."];\n";
  236. }
  237. if (!$this->inlineFactories) {
  238. foreach ($this->generateServiceFiles($services) as $file => [$c, $preload]) {
  239. $files[$file] = sprintf($fileTemplate, substr($file, 0, -4), $c);
  240. if ($preload) {
  241. $preloadedFiles[$file] = $file;
  242. }
  243. }
  244. foreach ($proxyClasses as $file => $c) {
  245. $files[$file] = "<?php\n".$c;
  246. $preloadedFiles[$file] = $file;
  247. }
  248. }
  249. $code .= $this->endClass();
  250. if ($this->inlineFactories) {
  251. foreach ($proxyClasses as $c) {
  252. $code .= $c;
  253. }
  254. }
  255. $files[$options['class'].'.php'] = $code;
  256. $preloadedFiles[$options['class'].'.php'] = $options['class'].'.php';
  257. $hash = ucfirst(strtr(ContainerBuilder::hash($files), '._', 'xx'));
  258. $code = [];
  259. foreach ($files as $file => $c) {
  260. $code["Container{$hash}/{$file}"] = substr_replace($c, "<?php\n\nnamespace Container{$hash};\n", 0, 6);
  261. if (isset($preloadedFiles[$file])) {
  262. $preloadedFiles[$file] = "Container{$hash}/{$file}";
  263. }
  264. }
  265. $namespaceLine = $this->namespace ? "\nnamespace {$this->namespace};\n" : '';
  266. $time = $options['build_time'];
  267. $id = hash('crc32', $hash.$time);
  268. $this->asFiles = false;
  269. if ($this->preload && null !== $autoloadFile = $this->getAutoloadFile()) {
  270. $autoloadFile = trim($this->export($autoloadFile), '()\\');
  271. $preloadedFiles = array_reverse($preloadedFiles);
  272. $preloadedFiles = implode("';\nrequire __DIR__.'/", $preloadedFiles);
  273. $code[$options['class'].'.preload.php'] = <<<EOF
  274. <?php
  275. // This file has been auto-generated by the Symfony Dependency Injection Component
  276. // You can reference it in the "opcache.preload" php.ini setting on PHP >= 7.4 when preloading is desired
  277. use Symfony\Component\DependencyInjection\Dumper\Preloader;
  278. if (in_array(PHP_SAPI, ['cli', 'phpdbg'], true)) {
  279. return;
  280. }
  281. require $autoloadFile;
  282. require __DIR__.'/$preloadedFiles';
  283. \$classes = [];
  284. EOF;
  285. foreach ($this->preload as $class) {
  286. if (!$class || false !== strpos($class, '$') || \in_array($class, ['int', 'float', 'string', 'bool', 'resource', 'object', 'array', 'null', 'callable', 'iterable', 'mixed', 'void'], true)) {
  287. continue;
  288. }
  289. if (!(class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false)) || (new \ReflectionClass($class))->isUserDefined()) {
  290. $code[$options['class'].'.preload.php'] .= sprintf("\$classes[] = '%s';\n", $class);
  291. }
  292. }
  293. $code[$options['class'].'.preload.php'] .= <<<'EOF'
  294. Preloader::preload($classes);
  295. EOF;
  296. }
  297. $code[$options['class'].'.php'] = <<<EOF
  298. <?php
  299. {$namespaceLine}
  300. // This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
  301. if (\\class_exists(\\Container{$hash}\\{$options['class']}::class, false)) {
  302. // no-op
  303. } elseif (!include __DIR__.'/Container{$hash}/{$options['class']}.php') {
  304. touch(__DIR__.'/Container{$hash}.legacy');
  305. return;
  306. }
  307. if (!\\class_exists({$options['class']}::class, false)) {
  308. \\class_alias(\\Container{$hash}\\{$options['class']}::class, {$options['class']}::class, false);
  309. }
  310. return new \\Container{$hash}\\{$options['class']}([
  311. 'container.build_hash' => '$hash',
  312. 'container.build_id' => '$id',
  313. 'container.build_time' => $time,
  314. ], __DIR__.\\DIRECTORY_SEPARATOR.'Container{$hash}');
  315. EOF;
  316. } else {
  317. $code .= $this->endClass();
  318. foreach ($proxyClasses as $c) {
  319. $code .= $c;
  320. }
  321. }
  322. $this->targetDirRegex = null;
  323. $this->inlinedRequires = [];
  324. $this->circularReferences = [];
  325. $this->locatedIds = [];
  326. $this->exportedVariables = [];
  327. $this->preload = [];
  328. $unusedEnvs = [];
  329. foreach ($this->container->getEnvCounters() as $env => $use) {
  330. if (!$use) {
  331. $unusedEnvs[] = $env;
  332. }
  333. }
  334. if ($unusedEnvs) {
  335. throw new EnvParameterException($unusedEnvs, null, 'Environment variables "%s" are never used. Please, check your container\'s configuration.');
  336. }
  337. return $code;
  338. }
  339. /**
  340. * Retrieves the currently set proxy dumper or instantiates one.
  341. */
  342. private function getProxyDumper(): ProxyDumper
  343. {
  344. if (!$this->proxyDumper) {
  345. $this->proxyDumper = new NullDumper();
  346. }
  347. return $this->proxyDumper;
  348. }
  349. private function analyzeReferences()
  350. {
  351. (new AnalyzeServiceReferencesPass(false, !$this->getProxyDumper() instanceof NullDumper))->process($this->container);
  352. $checkedNodes = [];
  353. $this->circularReferences = [];
  354. $this->singleUsePrivateIds = [];
  355. foreach ($this->container->getCompiler()->getServiceReferenceGraph()->getNodes() as $id => $node) {
  356. if (!$node->getValue() instanceof Definition) {
  357. continue;
  358. }
  359. if ($this->isSingleUsePrivateNode($node)) {
  360. $this->singleUsePrivateIds[$id] = $id;
  361. }
  362. $this->collectCircularReferences($id, $node->getOutEdges(), $checkedNodes);
  363. }
  364. $this->container->getCompiler()->getServiceReferenceGraph()->clear();
  365. $this->singleUsePrivateIds = array_diff_key($this->singleUsePrivateIds, $this->circularReferences);
  366. }
  367. private function collectCircularReferences(string $sourceId, array $edges, array &$checkedNodes, array &$loops = [], array $path = [], bool $byConstructor = true): void
  368. {
  369. $path[$sourceId] = $byConstructor;
  370. $checkedNodes[$sourceId] = true;
  371. foreach ($edges as $edge) {
  372. $node = $edge->getDestNode();
  373. $id = $node->getId();
  374. if ($sourceId === $id || !$node->getValue() instanceof Definition || $edge->isLazy() || $edge->isWeak()) {
  375. continue;
  376. }
  377. if (isset($path[$id])) {
  378. $loop = null;
  379. $loopByConstructor = $edge->isReferencedByConstructor();
  380. $pathInLoop = [$id, []];
  381. foreach ($path as $k => $pathByConstructor) {
  382. if (null !== $loop) {
  383. $loop[] = $k;
  384. $pathInLoop[1][$k] = $pathByConstructor;
  385. $loops[$k][] = &$pathInLoop;
  386. $loopByConstructor = $loopByConstructor && $pathByConstructor;
  387. } elseif ($k === $id) {
  388. $loop = [];
  389. }
  390. }
  391. $this->addCircularReferences($id, $loop, $loopByConstructor);
  392. } elseif (!isset($checkedNodes[$id])) {
  393. $this->collectCircularReferences($id, $node->getOutEdges(), $checkedNodes, $loops, $path, $edge->isReferencedByConstructor());
  394. } elseif (isset($loops[$id])) {
  395. // we already had detected loops for this edge
  396. // let's check if we have a common ancestor in one of the detected loops
  397. foreach ($loops[$id] as [$first, $loopPath]) {
  398. if (!isset($path[$first])) {
  399. continue;
  400. }
  401. // We have a common ancestor, let's fill the current path
  402. $fillPath = null;
  403. foreach ($loopPath as $k => $pathByConstructor) {
  404. if (null !== $fillPath) {
  405. $fillPath[$k] = $pathByConstructor;
  406. } elseif ($k === $id) {
  407. $fillPath = $path;
  408. $fillPath[$k] = $pathByConstructor;
  409. }
  410. }
  411. // we can now build the loop
  412. $loop = null;
  413. $loopByConstructor = $edge->isReferencedByConstructor();
  414. foreach ($fillPath as $k => $pathByConstructor) {
  415. if (null !== $loop) {
  416. $loop[] = $k;
  417. $loopByConstructor = $loopByConstructor && $pathByConstructor;
  418. } elseif ($k === $first) {
  419. $loop = [];
  420. }
  421. }
  422. $this->addCircularReferences($first, $loop, true);
  423. break;
  424. }
  425. }
  426. }
  427. unset($path[$sourceId]);
  428. }
  429. private function addCircularReferences(string $sourceId, array $currentPath, bool $byConstructor)
  430. {
  431. $currentId = $sourceId;
  432. $currentPath = array_reverse($currentPath);
  433. $currentPath[] = $currentId;
  434. foreach ($currentPath as $parentId) {
  435. if (empty($this->circularReferences[$parentId][$currentId])) {
  436. $this->circularReferences[$parentId][$currentId] = $byConstructor;
  437. }
  438. $currentId = $parentId;
  439. }
  440. }
  441. private function collectLineage(string $class, array &$lineage)
  442. {
  443. if (isset($lineage[$class])) {
  444. return;
  445. }
  446. if (!$r = $this->container->getReflectionClass($class, false)) {
  447. return;
  448. }
  449. if (is_a($class, $this->baseClass, true)) {
  450. return;
  451. }
  452. $file = $r->getFileName();
  453. if (') : eval()\'d code' === substr($file, -17)) {
  454. $file = substr($file, 0, strrpos($file, '(', -17));
  455. }
  456. if (!$file || $this->doExport($file) === $exportedFile = $this->export($file)) {
  457. return;
  458. }
  459. $lineage[$class] = substr($exportedFile, 1, -1);
  460. if ($parent = $r->getParentClass()) {
  461. $this->collectLineage($parent->name, $lineage);
  462. }
  463. foreach ($r->getInterfaces() as $parent) {
  464. $this->collectLineage($parent->name, $lineage);
  465. }
  466. foreach ($r->getTraits() as $parent) {
  467. $this->collectLineage($parent->name, $lineage);
  468. }
  469. unset($lineage[$class]);
  470. $lineage[$class] = substr($exportedFile, 1, -1);
  471. }
  472. private function generateProxyClasses(): array
  473. {
  474. $proxyClasses = [];
  475. $alreadyGenerated = [];
  476. $definitions = $this->container->getDefinitions();
  477. $strip = '' === $this->docStar && method_exists(Kernel::class, 'stripComments');
  478. $proxyDumper = $this->getProxyDumper();
  479. ksort($definitions);
  480. foreach ($definitions as $definition) {
  481. if (!$proxyDumper->isProxyCandidate($definition)) {
  482. continue;
  483. }
  484. if (isset($alreadyGenerated[$class = $definition->getClass()])) {
  485. continue;
  486. }
  487. $alreadyGenerated[$class] = true;
  488. // register class' reflector for resource tracking
  489. $this->container->getReflectionClass($class);
  490. if ("\n" === $proxyCode = "\n".$proxyDumper->getProxyCode($definition)) {
  491. continue;
  492. }
  493. if ($this->inlineRequires) {
  494. $lineage = [];
  495. $this->collectLineage($class, $lineage);
  496. $code = '';
  497. foreach (array_diff_key(array_flip($lineage), $this->inlinedRequires) as $file => $class) {
  498. if ($this->inlineFactories) {
  499. $this->inlinedRequires[$file] = true;
  500. }
  501. $code .= sprintf("include_once %s;\n", $file);
  502. }
  503. $proxyCode = $code.$proxyCode;
  504. }
  505. if ($strip) {
  506. $proxyCode = "<?php\n".$proxyCode;
  507. $proxyCode = substr(Kernel::stripComments($proxyCode), 5);
  508. }
  509. $proxyClass = explode(' ', $this->inlineRequires ? substr($proxyCode, \strlen($code)) : $proxyCode, 3)[1];
  510. if ($this->asFiles || $this->namespace) {
  511. $proxyCode .= "\nif (!\\class_exists('$proxyClass', false)) {\n \\class_alias(__NAMESPACE__.'\\\\$proxyClass', '$proxyClass', false);\n}\n";
  512. }
  513. $proxyClasses[$proxyClass.'.php'] = $proxyCode;
  514. }
  515. return $proxyClasses;
  516. }
  517. private function addServiceInclude(string $cId, Definition $definition): string
  518. {
  519. $code = '';
  520. if ($this->inlineRequires && (!$this->isHotPath($definition) || $this->getProxyDumper()->isProxyCandidate($definition))) {
  521. $lineage = [];
  522. foreach ($this->inlinedDefinitions as $def) {
  523. if (!$def->isDeprecated()) {
  524. foreach ($this->getClasses($def, $cId) as $class) {
  525. $this->collectLineage($class, $lineage);
  526. }
  527. }
  528. }
  529. foreach ($this->serviceCalls as $id => [$callCount, $behavior]) {
  530. if ('service_container' !== $id && $id !== $cId
  531. && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $behavior
  532. && $this->container->has($id)
  533. && $this->isTrivialInstance($def = $this->container->findDefinition($id))
  534. ) {
  535. foreach ($this->getClasses($def, $cId) as $class) {
  536. $this->collectLineage($class, $lineage);
  537. }
  538. }
  539. }
  540. foreach (array_diff_key(array_flip($lineage), $this->inlinedRequires) as $file => $class) {
  541. $code .= sprintf(" include_once %s;\n", $file);
  542. }
  543. }
  544. foreach ($this->inlinedDefinitions as $def) {
  545. if ($file = $def->getFile()) {
  546. $file = $this->dumpValue($file);
  547. $file = '(' === $file[0] ? substr($file, 1, -1) : $file;
  548. $code .= sprintf(" include_once %s;\n", $file);
  549. }
  550. }
  551. if ('' !== $code) {
  552. $code .= "\n";
  553. }
  554. return $code;
  555. }
  556. /**
  557. * @throws InvalidArgumentException
  558. * @throws RuntimeException
  559. */
  560. private function addServiceInstance(string $id, Definition $definition, bool $isSimpleInstance): string
  561. {
  562. $class = $this->dumpValue($definition->getClass());
  563. 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)) {
  564. throw new InvalidArgumentException(sprintf('"%s" is not a valid class name for the "%s" service.', $class, $id));
  565. }
  566. $isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition);
  567. $instantiation = '';
  568. $lastWitherIndex = null;
  569. foreach ($definition->getMethodCalls() as $k => $call) {
  570. if ($call[2] ?? false) {
  571. $lastWitherIndex = $k;
  572. }
  573. }
  574. if (!$isProxyCandidate && $definition->isShared() && !isset($this->singleUsePrivateIds[$id]) && null === $lastWitherIndex) {
  575. $instantiation = sprintf('$this->%s[%s] = %s', $this->container->getDefinition($id)->isPublic() ? 'services' : 'privates', $this->doExport($id), $isSimpleInstance ? '' : '$instance');
  576. } elseif (!$isSimpleInstance) {
  577. $instantiation = '$instance';
  578. }
  579. $return = '';
  580. if ($isSimpleInstance) {
  581. $return = 'return ';
  582. } else {
  583. $instantiation .= ' = ';
  584. }
  585. return $this->addNewInstance($definition, ' '.$return.$instantiation, $id);
  586. }
  587. private function isTrivialInstance(Definition $definition): bool
  588. {
  589. if ($definition->hasErrors()) {
  590. return true;
  591. }
  592. if ($definition->isSynthetic() || $definition->getFile() || $definition->getMethodCalls() || $definition->getProperties() || $definition->getConfigurator()) {
  593. return false;
  594. }
  595. if ($definition->isDeprecated() || $definition->isLazy() || $definition->getFactory() || 3 < \count($definition->getArguments())) {
  596. return false;
  597. }
  598. foreach ($definition->getArguments() as $arg) {
  599. if (!$arg || $arg instanceof Parameter) {
  600. continue;
  601. }
  602. if (\is_array($arg) && 3 >= \count($arg)) {
  603. foreach ($arg as $k => $v) {
  604. if ($this->dumpValue($k) !== $this->dumpValue($k, false)) {
  605. return false;
  606. }
  607. if (!$v || $v instanceof Parameter) {
  608. continue;
  609. }
  610. if ($v instanceof Reference && $this->container->has($id = (string) $v) && $this->container->findDefinition($id)->isSynthetic()) {
  611. continue;
  612. }
  613. if (!is_scalar($v) || $this->dumpValue($v) !== $this->dumpValue($v, false)) {
  614. return false;
  615. }
  616. }
  617. } elseif ($arg instanceof Reference && $this->container->has($id = (string) $arg) && $this->container->findDefinition($id)->isSynthetic()) {
  618. continue;
  619. } elseif (!is_scalar($arg) || $this->dumpValue($arg) !== $this->dumpValue($arg, false)) {
  620. return false;
  621. }
  622. }
  623. return true;
  624. }
  625. private function addServiceMethodCalls(Definition $definition, string $variableName, ?string $sharedNonLazyId): string
  626. {
  627. $lastWitherIndex = null;
  628. foreach ($definition->getMethodCalls() as $k => $call) {
  629. if ($call[2] ?? false) {
  630. $lastWitherIndex = $k;
  631. }
  632. }
  633. $calls = '';
  634. foreach ($definition->getMethodCalls() as $k => $call) {
  635. $arguments = [];
  636. foreach ($call[1] as $value) {
  637. $arguments[] = $this->dumpValue($value);
  638. }
  639. $witherAssignation = '';
  640. if ($call[2] ?? false) {
  641. if (null !== $sharedNonLazyId && $lastWitherIndex === $k) {
  642. $witherAssignation = sprintf('$this->%s[\'%s\'] = ', $definition->isPublic() ? 'services' : 'privates', $sharedNonLazyId);
  643. }
  644. $witherAssignation .= sprintf('$%s = ', $variableName);
  645. }
  646. $calls .= $this->wrapServiceConditionals($call[1], sprintf(" %s\$%s->%s(%s);\n", $witherAssignation, $variableName, $call[0], implode(', ', $arguments)));
  647. }
  648. return $calls;
  649. }
  650. private function addServiceProperties(Definition $definition, string $variableName = 'instance'): string
  651. {
  652. $code = '';
  653. foreach ($definition->getProperties() as $name => $value) {
  654. $code .= sprintf(" \$%s->%s = %s;\n", $variableName, $name, $this->dumpValue($value));
  655. }
  656. return $code;
  657. }
  658. private function addServiceConfigurator(Definition $definition, string $variableName = 'instance'): string
  659. {
  660. if (!$callable = $definition->getConfigurator()) {
  661. return '';
  662. }
  663. if (\is_array($callable)) {
  664. if ($callable[0] instanceof Reference
  665. || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))
  666. ) {
  667. return sprintf(" %s->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
  668. }
  669. $class = $this->dumpValue($callable[0]);
  670. // If the class is a string we can optimize away
  671. if (0 === strpos($class, "'") && false === strpos($class, '$')) {
  672. return sprintf(" %s::%s(\$%s);\n", $this->dumpLiteralClass($class), $callable[1], $variableName);
  673. }
  674. if (0 === strpos($class, 'new ')) {
  675. return sprintf(" (%s)->%s(\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
  676. }
  677. return sprintf(" [%s, '%s'](\$%s);\n", $this->dumpValue($callable[0]), $callable[1], $variableName);
  678. }
  679. return sprintf(" %s(\$%s);\n", $callable, $variableName);
  680. }
  681. private function addService(string $id, Definition $definition): array
  682. {
  683. $this->definitionVariables = new \SplObjectStorage();
  684. $this->referenceVariables = [];
  685. $this->variableCount = 0;
  686. $this->referenceVariables[$id] = new Variable('instance');
  687. $return = [];
  688. if ($class = $definition->getClass()) {
  689. $class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class);
  690. $return[] = sprintf(0 === strpos($class, '%') ? '@return object A %1$s instance' : '@return \%s', ltrim($class, '\\'));
  691. } elseif ($definition->getFactory()) {
  692. $factory = $definition->getFactory();
  693. if (\is_string($factory)) {
  694. $return[] = sprintf('@return object An instance returned by %s()', $factory);
  695. } elseif (\is_array($factory) && (\is_string($factory[0]) || $factory[0] instanceof Definition || $factory[0] instanceof Reference)) {
  696. $class = $factory[0] instanceof Definition ? $factory[0]->getClass() : (string) $factory[0];
  697. $class = $class instanceof Parameter ? '%'.$class.'%' : $this->container->resolveEnvPlaceholders($class);
  698. $return[] = sprintf('@return object An instance returned by %s::%s()', $class, $factory[1]);
  699. }
  700. }
  701. if ($definition->isDeprecated()) {
  702. if ($return && 0 === strpos($return[\count($return) - 1], '@return')) {
  703. $return[] = '';
  704. }
  705. $deprecation = $definition->getDeprecation($id);
  706. $return[] = sprintf('@deprecated %s', ($deprecation['package'] || $deprecation['version'] ? "Since {$deprecation['package']} {$deprecation['version']}: " : '').$deprecation['message']);
  707. }
  708. $return = str_replace("\n * \n", "\n *\n", implode("\n * ", $return));
  709. $return = $this->container->resolveEnvPlaceholders($return);
  710. $shared = $definition->isShared() ? ' shared' : '';
  711. $public = $definition->isPublic() ? 'public' : 'private';
  712. $autowired = $definition->isAutowired() ? ' autowired' : '';
  713. $asFile = $this->asFiles && !$this->inlineFactories && !$this->isHotPath($definition);
  714. $methodName = $this->generateMethodName($id);
  715. if ($asFile || $definition->isLazy()) {
  716. $lazyInitialization = '$lazyLoad = true';
  717. } else {
  718. $lazyInitialization = '';
  719. }
  720. $code = <<<EOF
  721. /*{$this->docStar}
  722. * Gets the $public '$id'$shared$autowired service.
  723. *
  724. * $return
  725. EOF;
  726. $code = str_replace('*/', ' ', $code).<<<EOF
  727. */
  728. protected function {$methodName}($lazyInitialization)
  729. {
  730. EOF;
  731. if ($asFile) {
  732. $file = $methodName.'.php';
  733. $code = str_replace("protected function {$methodName}(", 'public static function do($container, ', $code);
  734. } else {
  735. $file = null;
  736. }
  737. if ($definition->hasErrors() && $e = $definition->getErrors()) {
  738. $this->addThrow = true;
  739. $code .= sprintf(" \$this->throw(%s);\n", $this->export(reset($e)));
  740. } else {
  741. $this->serviceCalls = [];
  742. $this->inlinedDefinitions = $this->getDefinitionsFromArguments([$definition], null, $this->serviceCalls);
  743. if ($definition->isDeprecated()) {
  744. $deprecation = $definition->getDeprecation($id);
  745. $code .= sprintf(" trigger_deprecation(%s, %s, %s);\n\n", $this->export($deprecation['package']), $this->export($deprecation['version']), $this->export($deprecation['message']));
  746. } elseif ($definition->hasTag($this->hotPathTag) || !$definition->hasTag($this->preloadTags[1])) {
  747. foreach ($this->inlinedDefinitions as $def) {
  748. foreach ($this->getClasses($def, $id) as $class) {
  749. $this->preload[$class] = $class;
  750. }
  751. }
  752. }
  753. if (!$definition->isShared()) {
  754. $factory = sprintf('$this->factories%s[%s]', $definition->isPublic() ? '' : "['service_container']", $this->doExport($id));
  755. }
  756. if ($isProxyCandidate = $this->getProxyDumper()->isProxyCandidate($definition)) {
  757. if (!$definition->isShared()) {
  758. $code .= sprintf(' %s = %1$s ?? ', $factory);
  759. if ($asFile) {
  760. $code .= "function () {\n";
  761. $code .= " return self::do(\$container);\n";
  762. $code .= " };\n\n";
  763. } else {
  764. $code .= sprintf("\\Closure::fromCallable([\$this, '%s']);\n\n", $methodName);
  765. }
  766. }
  767. $factoryCode = $asFile ? 'self::do($container, false)' : sprintf('$this->%s(false)', $methodName);
  768. $factoryCode = $this->getProxyDumper()->getProxyFactoryCode($definition, $id, $factoryCode);
  769. $code .= $asFile ? preg_replace('/function \(([^)]*+)\)( {|:)/', 'function (\1) use ($container)\2', $factoryCode) : $factoryCode;
  770. }
  771. $c = $this->addServiceInclude($id, $definition);
  772. if ('' !== $c && $isProxyCandidate && !$definition->isShared()) {
  773. $c = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $c)));
  774. $code .= " static \$include = true;\n\n";
  775. $code .= " if (\$include) {\n";
  776. $code .= $c;
  777. $code .= " \$include = false;\n";
  778. $code .= " }\n\n";
  779. } else {
  780. $code .= $c;
  781. }
  782. $c = $this->addInlineService($id, $definition);
  783. if (!$isProxyCandidate && !$definition->isShared()) {
  784. $c = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $c)));
  785. $lazyloadInitialization = $definition->isLazy() ? '$lazyLoad = true' : '';
  786. $c = sprintf(" %s = function (%s) {\n%s };\n\n return %1\$s();\n", $factory, $lazyloadInitialization, $c);
  787. }
  788. $code .= $c;
  789. }
  790. if ($asFile) {
  791. $code = str_replace('$this', '$container', $code);
  792. $code = preg_replace('/function \(([^)]*+)\)( {|:)/', 'function (\1) use ($container)\2', $code);
  793. }
  794. $code .= " }\n";
  795. $this->definitionVariables = $this->inlinedDefinitions = null;
  796. $this->referenceVariables = $this->serviceCalls = null;
  797. return [$file, $code];
  798. }
  799. private function addInlineVariables(string $id, Definition $definition, array $arguments, bool $forConstructor): string
  800. {
  801. $code = '';
  802. foreach ($arguments as $argument) {
  803. if (\is_array($argument)) {
  804. $code .= $this->addInlineVariables($id, $definition, $argument, $forConstructor);
  805. } elseif ($argument instanceof Reference) {
  806. $code .= $this->addInlineReference($id, $definition, $argument, $forConstructor);
  807. } elseif ($argument instanceof Definition) {
  808. $code .= $this->addInlineService($id, $definition, $argument, $forConstructor);
  809. }
  810. }
  811. return $code;
  812. }
  813. private function addInlineReference(string $id, Definition $definition, string $targetId, bool $forConstructor): string
  814. {
  815. while ($this->container->hasAlias($targetId)) {
  816. $targetId = (string) $this->container->getAlias($targetId);
  817. }
  818. [$callCount, $behavior] = $this->serviceCalls[$targetId];
  819. if ($id === $targetId) {
  820. return $this->addInlineService($id, $definition, $definition);
  821. }
  822. if ('service_container' === $targetId || isset($this->referenceVariables[$targetId])) {
  823. return '';
  824. }
  825. if ($this->container->hasDefinition($targetId) && ($def = $this->container->getDefinition($targetId)) && !$def->isShared()) {
  826. return '';
  827. }
  828. $hasSelfRef = isset($this->circularReferences[$id][$targetId]) && !isset($this->definitionVariables[$definition]);
  829. if ($hasSelfRef && !$forConstructor && !$forConstructor = !$this->circularReferences[$id][$targetId]) {
  830. $code = $this->addInlineService($id, $definition, $definition);
  831. } else {
  832. $code = '';
  833. }
  834. if (isset($this->referenceVariables[$targetId]) || (2 > $callCount && (!$hasSelfRef || !$forConstructor))) {
  835. return $code;
  836. }
  837. $name = $this->getNextVariableName();
  838. $this->referenceVariables[$targetId] = new Variable($name);
  839. $reference = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE >= $behavior ? new Reference($targetId, $behavior) : null;
  840. $code .= sprintf(" \$%s = %s;\n", $name, $this->getServiceCall($targetId, $reference));
  841. if (!$hasSelfRef || !$forConstructor) {
  842. return $code;
  843. }
  844. $code .= sprintf(<<<'EOTXT'
  845. if (isset($this->%s[%s])) {
  846. return $this->%1$s[%2$s];
  847. }
  848. EOTXT
  849. ,
  850. $this->container->getDefinition($id)->isPublic() ? 'services' : 'privates',
  851. $this->doExport($id)
  852. );
  853. return $code;
  854. }
  855. private function addInlineService(string $id, Definition $definition, Definition $inlineDef = null, bool $forConstructor = true): string
  856. {
  857. $code = '';
  858. if ($isSimpleInstance = $isRootInstance = null === $inlineDef) {
  859. foreach ($this->serviceCalls as $targetId => [$callCount, $behavior, $byConstructor]) {
  860. if ($byConstructor && isset($this->circularReferences[$id][$targetId]) && !$this->circularReferences[$id][$targetId]) {
  861. $code .= $this->addInlineReference($id, $definition, $targetId, $forConstructor);
  862. }
  863. }
  864. }
  865. if (isset($this->definitionVariables[$inlineDef = $inlineDef ?: $definition])) {
  866. return $code;
  867. }
  868. $arguments = [$inlineDef->getArguments(), $inlineDef->getFactory()];
  869. $code .= $this->addInlineVariables($id, $definition, $arguments, $forConstructor);
  870. if ($arguments = array_filter([$inlineDef->getProperties(), $inlineDef->getMethodCalls(), $inlineDef->getConfigurator()])) {
  871. $isSimpleInstance = false;
  872. } elseif ($definition !== $inlineDef && 2 > $this->inlinedDefinitions[$inlineDef]) {
  873. return $code;
  874. }
  875. if (isset($this->definitionVariables[$inlineDef])) {
  876. $isSimpleInstance = false;
  877. } else {
  878. $name = $definition === $inlineDef ? 'instance' : $this->getNextVariableName();
  879. $this->definitionVariables[$inlineDef] = new Variable($name);
  880. $code .= '' !== $code ? "\n" : '';
  881. if ('instance' === $name) {
  882. $code .= $this->addServiceInstance($id, $definition, $isSimpleInstance);
  883. } else {
  884. $code .= $this->addNewInstance($inlineDef, ' $'.$name.' = ', $id);
  885. }
  886. if ('' !== $inline = $this->addInlineVariables($id, $definition, $arguments, false)) {
  887. $code .= "\n".$inline."\n";
  888. } elseif ($arguments && 'instance' === $name) {
  889. $code .= "\n";
  890. }
  891. $code .= $this->addServiceProperties($inlineDef, $name);
  892. $code .= $this->addServiceMethodCalls($inlineDef, $name, !$this->getProxyDumper()->isProxyCandidate($inlineDef) && $inlineDef->isShared() && !isset($this->singleUsePrivateIds[$id]) ? $id : null);
  893. $code .= $this->addServiceConfigurator($inlineDef, $name);
  894. }
  895. if ($isRootInstance && !$isSimpleInstance) {
  896. $code .= "\n return \$instance;\n";
  897. }
  898. return $code;
  899. }
  900. private function addServices(array &$services = null): string
  901. {
  902. $publicServices = $privateServices = '';
  903. $definitions = $this->container->getDefinitions();
  904. ksort($definitions);
  905. foreach ($definitions as $id => $definition) {
  906. if (!$definition->isSynthetic()) {
  907. $services[$id] = $this->addService($id, $definition);
  908. } elseif ($definition->hasTag($this->hotPathTag) || !$definition->hasTag($this->preloadTags[1])) {
  909. $services[$id] = null;
  910. foreach ($this->getClasses($definition, $id) as $class) {
  911. $this->preload[$class] = $class;
  912. }
  913. }
  914. }
  915. foreach ($definitions as $id => $definition) {
  916. if (!([$file, $code] = $services[$id]) || null !== $file) {
  917. continue;
  918. }
  919. if ($definition->isPublic()) {
  920. $publicServices .= $code;
  921. } elseif (!$this->isTrivialInstance($definition) || isset($this->locatedIds[$id])) {
  922. $privateServices .= $code;
  923. }
  924. }
  925. return $publicServices.$privateServices;
  926. }
  927. private function generateServiceFiles(array $services): iterable
  928. {
  929. $definitions = $this->container->getDefinitions();
  930. ksort($definitions);
  931. foreach ($definitions as $id => $definition) {
  932. if (([$file, $code] = $services[$id]) && null !== $file && ($definition->isPublic() || !$this->isTrivialInstance($definition) || isset($this->locatedIds[$id]))) {
  933. yield $file => [$code, $definition->hasTag($this->hotPathTag) || !$definition->hasTag($this->preloadTags[1]) && !$definition->isDeprecated() && !$definition->hasErrors()];
  934. }
  935. }
  936. }
  937. private function addNewInstance(Definition $definition, string $return = '', string $id = null): string
  938. {
  939. $tail = $return ? ";\n" : '';
  940. if (BaseServiceLocator::class === $definition->getClass() && $definition->hasTag($this->serviceLocatorTag)) {
  941. $arguments = [];
  942. foreach ($definition->getArgument(0) as $k => $argument) {
  943. $arguments[$k] = $argument->getValues()[0];
  944. }
  945. return $return.$this->dumpValue(new ServiceLocatorArgument($arguments)).$tail;
  946. }
  947. $arguments = [];
  948. foreach ($definition->getArguments() as $value) {
  949. $arguments[] = $this->dumpValue($value);
  950. }
  951. if (null !== $definition->getFactory()) {
  952. $callable = $definition->getFactory();
  953. if (\is_array($callable)) {
  954. if (!preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $callable[1])) {
  955. throw new RuntimeException(sprintf('Cannot dump definition because of invalid factory method (%s).', $callable[1] ?: 'n/a'));
  956. }
  957. if ($callable[0] instanceof Reference
  958. || ($callable[0] instanceof Definition && $this->definitionVariables->contains($callable[0]))) {
  959. return $return.sprintf('%s->%s(%s)', $this->dumpValue($callable[0]), $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
  960. }
  961. $class = $this->dumpValue($callable[0]);
  962. // If the class is a string we can optimize away
  963. if (0 === strpos($class, "'") && false === strpos($class, '$')) {
  964. if ("''" === $class) {
  965. throw new RuntimeException(sprintf('Cannot dump definition: "%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 ? 'The "'.$id.'"' : 'inline'));
  966. }
  967. return $return.sprintf('%s::%s(%s)', $this->dumpLiteralClass($class), $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
  968. }
  969. if (0 === strpos($class, 'new ')) {
  970. return $return.sprintf('(%s)->%s(%s)', $class, $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
  971. }
  972. return $return.sprintf("[%s, '%s'](%s)", $class, $callable[1], $arguments ? implode(', ', $arguments) : '').$tail;
  973. }
  974. return $return.sprintf('%s(%s)', $this->dumpLiteralClass($this->dumpValue($callable)), $arguments ? implode(', ', $arguments) : '').$tail;
  975. }
  976. if (null === $class = $definition->getClass()) {
  977. throw new RuntimeException('Cannot dump definitions which have no class nor factory.');
  978. }
  979. return $return.sprintf('new %s(%s)', $this->dumpLiteralClass($this->dumpValue($class)), implode(', ', $arguments)).$tail;
  980. }
  981. private function startClass(string $class, string $baseClass): string
  982. {
  983. $namespaceLine = !$this->asFiles && $this->namespace ? "\nnamespace {$this->namespace};\n" : '';
  984. $code = <<<EOF
  985. <?php
  986. $namespaceLine
  987. use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
  988. use Symfony\Component\DependencyInjection\ContainerInterface;
  989. use Symfony\Component\DependencyInjection\Container;
  990. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  991. use Symfony\Component\DependencyInjection\Exception\LogicException;
  992. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  993. use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
  994. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  995. /*{$this->docStar}
  996. * @internal This class has been auto-generated by the Symfony Dependency Injection Component.
  997. */
  998. class $class extends $baseClass
  999. {
  1000. protected \$parameters = [];
  1001. public function __construct()
  1002. {
  1003. EOF;
  1004. if ($this->asFiles) {
  1005. $code = str_replace('$parameters = []', "\$containerDir;\n protected \$parameters = [];\n private \$buildParameters", $code);
  1006. $code = str_replace('__construct()', '__construct(array $buildParameters = [], $containerDir = __DIR__)', $code);
  1007. $code .= " \$this->buildParameters = \$buildParameters;\n";
  1008. $code .= " \$this->containerDir = \$containerDir;\n";
  1009. if (null !== $this->targetDirRegex) {
  1010. $code = str_replace('$parameters = []', "\$targetDir;\n protected \$parameters = []", $code);
  1011. $code .= ' $this->targetDir = \\dirname($containerDir);'."\n";
  1012. }
  1013. }
  1014. if (Container::class !== $this->baseClass) {
  1015. $r = $this->container->getReflectionClass($this->baseClass, false);
  1016. if (null !== $r
  1017. && (null !== $constructor = $r->getConstructor())
  1018. && 0 === $constructor->getNumberOfRequiredParameters()
  1019. && Container::class !== $constructor->getDeclaringClass()->name
  1020. ) {
  1021. $code .= " parent::__construct();\n";
  1022. $code .= " \$this->parameterBag = null;\n\n";
  1023. }
  1024. }
  1025. if ($this->container->getParameterBag()->all()) {
  1026. $code .= " \$this->parameters = \$this->getDefaultParameters();\n\n";
  1027. }
  1028. $code .= " \$this->services = \$this->privates = [];\n";
  1029. $code .= $this->addSyntheticIds();
  1030. $code .= $this->addMethodMap();
  1031. $code .= $this->asFiles && !$this->inlineFactories ? $this->addFileMap() : '';
  1032. $code .= $this->addAliases();
  1033. $code .= $this->addInlineRequires();
  1034. $code .= <<<EOF
  1035. }
  1036. public function compile(): void
  1037. {
  1038. throw new LogicException('You cannot compile a dumped container that was already compiled.');
  1039. }
  1040. public function isCompiled(): bool
  1041. {
  1042. return true;
  1043. }
  1044. EOF;
  1045. $code .= $this->addRemovedIds();
  1046. if ($this->asFiles && !$this->inlineFactories) {
  1047. $code .= <<<'EOF'
  1048. protected function load($file, $lazyLoad = true)
  1049. {
  1050. if (class_exists($class = __NAMESPACE__.'\\'.$file, false)) {
  1051. return $class::do($this, $lazyLoad);
  1052. }
  1053. if ('.' === $file[-4]) {
  1054. $class = substr($class, 0, -4);
  1055. } else {
  1056. $file .= '.php';
  1057. }
  1058. $service = require $this->containerDir.\DIRECTORY_SEPARATOR.$file;
  1059. return class_exists($class, false) ? $class::do($this, $lazyLoad) : $service;
  1060. }
  1061. EOF;
  1062. }
  1063. $proxyDumper = $this->getProxyDumper();
  1064. foreach ($this->container->getDefinitions() as $definition) {
  1065. if (!$proxyDumper->isProxyCandidate($definition)) {
  1066. continue;
  1067. }
  1068. if ($this->asFiles && !$this->inlineFactories) {
  1069. $proxyLoader = "class_exists(\$class, false) || require __DIR__.'/'.\$class.'.php';\n\n ";
  1070. } else {
  1071. $proxyLoader = '';
  1072. }
  1073. $code .= <<<EOF
  1074. protected function createProxy(\$class, \Closure \$factory)
  1075. {
  1076. {$proxyLoader}return \$factory();
  1077. }
  1078. EOF;
  1079. break;
  1080. }
  1081. return $code;
  1082. }
  1083. private function addSyntheticIds(): string
  1084. {
  1085. $code = '';
  1086. $definitions = $this->container->getDefinitions();
  1087. ksort($definitions);
  1088. foreach ($definitions as $id => $definition) {
  1089. if ($definition->isSynthetic() && 'service_container' !== $id) {
  1090. $code .= ' '.$this->doExport($id)." => true,\n";
  1091. }
  1092. }
  1093. return $code ? " \$this->syntheticIds = [\n{$code} ];\n" : '';
  1094. }
  1095. private function addRemovedIds(): string
  1096. {
  1097. $ids = $this->container->getRemovedIds();
  1098. foreach ($this->container->getDefinitions() as $id => $definition) {
  1099. if (!$definition->isPublic()) {
  1100. $ids[$id] = true;
  1101. }
  1102. }
  1103. if (!$ids) {
  1104. return '';
  1105. }
  1106. if ($this->asFiles) {
  1107. $code = "require \$this->containerDir.\\DIRECTORY_SEPARATOR.'removed-ids.php'";
  1108. } else {
  1109. $code = '';
  1110. $ids = array_keys($ids);
  1111. sort($ids);
  1112. foreach ($ids as $id) {
  1113. if (preg_match(FileLoader::ANONYMOUS_ID_REGEXP, $id)) {
  1114. continue;
  1115. }
  1116. $code .= ' '.$this->doExport($id)." => true,\n";
  1117. }
  1118. $code = "[\n{$code} ]";
  1119. }
  1120. return <<<EOF
  1121. public function getRemovedIds(): array
  1122. {
  1123. return {$code};
  1124. }
  1125. EOF;
  1126. }
  1127. private function addMethodMap(): string
  1128. {
  1129. $code = '';
  1130. $definitions = $this->container->getDefinitions();
  1131. ksort($definitions);
  1132. foreach ($definitions as $id => $definition) {
  1133. if (!$definition->isSynthetic() && $definition->isPublic() && (!$this->asFiles || $this->inlineFactories || $this->isHotPath($definition))) {
  1134. $code .= ' '.$this->doExport($id).' => '.$this->doExport($this->generateMethodName($id)).",\n";
  1135. }
  1136. }
  1137. $aliases = $this->container->getAliases();
  1138. foreach ($aliases as $alias => $id) {
  1139. if (!$id->isDeprecated()) {
  1140. continue;
  1141. }
  1142. $code .= ' '.$this->doExport($alias).' => '.$this->doExport($this->generateMethodName($alias)).",\n";
  1143. }
  1144. return $code ? " \$this->methodMap = [\n{$code} ];\n" : '';
  1145. }
  1146. private function addFileMap(): string
  1147. {
  1148. $code = '';
  1149. $definitions = $this->container->getDefinitions();
  1150. ksort($definitions);
  1151. foreach ($definitions as $id => $definition) {
  1152. if (!$definition->isSynthetic() && $definition->isPublic() && !$this->isHotPath($definition)) {
  1153. $code .= sprintf(" %s => '%s',\n", $this->doExport($id), $this->generateMethodName($id));
  1154. }
  1155. }
  1156. return $code ? " \$this->fileMap = [\n{$code} ];\n" : '';
  1157. }
  1158. private function addAliases(): string
  1159. {
  1160. if (!$aliases = $this->container->getAliases()) {
  1161. return "\n \$this->aliases = [];\n";
  1162. }
  1163. $code = " \$this->aliases = [\n";
  1164. ksort($aliases);
  1165. foreach ($aliases as $alias => $id) {
  1166. if ($id->isDeprecated()) {
  1167. continue;
  1168. }
  1169. $id = (string) $id;
  1170. while (isset($aliases[$id])) {
  1171. $id = (string) $aliases[$id];
  1172. }
  1173. $code .= ' '.$this->doExport($alias).' => '.$this->doExport($id).",\n";
  1174. }
  1175. return $code." ];\n";
  1176. }
  1177. private function addDeprecatedAliases(): string
  1178. {
  1179. $code = '';
  1180. $aliases = $this->container->getAliases();
  1181. foreach ($aliases as $alias => $definition) {
  1182. if (!$definition->isDeprecated()) {
  1183. continue;
  1184. }
  1185. $public = $definition->isPublic() ? 'public' : 'private';
  1186. $id = (string) $definition;
  1187. $methodNameAlias = $this->generateMethodName($alias);
  1188. $idExported = $this->export($id);
  1189. $deprecation = $definition->getDeprecation($alias);
  1190. $packageExported = $this->export($deprecation['package']);
  1191. $versionExported = $this->export($deprecation['version']);
  1192. $messageExported = $this->export($deprecation['message']);
  1193. $code .= <<<EOF
  1194. /*{$this->docStar}
  1195. * Gets the $public '$alias' alias.
  1196. *
  1197. * @return object The "$id" service.
  1198. */
  1199. protected function {$methodNameAlias}()
  1200. {
  1201. trigger_deprecation($packageExported, $versionExported, $messageExported);
  1202. return \$this->get($idExported);
  1203. }
  1204. EOF;
  1205. }
  1206. return $code;
  1207. }
  1208. private function addInlineRequires(): string
  1209. {
  1210. if (!$this->hotPathTag || !$this->inlineRequires) {
  1211. return '';
  1212. }
  1213. $lineage = [];
  1214. foreach ($this->container->findTaggedServiceIds($this->hotPathTag) as $id => $tags) {
  1215. $definition = $this->container->getDefinition($id);
  1216. if ($this->getProxyDumper()->isProxyCandidate($definition)) {
  1217. continue;
  1218. }
  1219. $inlinedDefinitions = $this->getDefinitionsFromArguments([$definition]);
  1220. foreach ($inlinedDefinitions as $def) {
  1221. foreach ($this->getClasses($def, $id) as $class) {
  1222. $this->collectLineage($class, $lineage);
  1223. }
  1224. }
  1225. }
  1226. $code = '';
  1227. foreach ($lineage as $file) {
  1228. if (!isset($this->inlinedRequires[$file])) {
  1229. $this->inlinedRequires[$file] = true;
  1230. $code .= sprintf("\n include_once %s;", $file);
  1231. }
  1232. }
  1233. return $code ? sprintf("\n \$this->privates['service_container'] = function () {%s\n };\n", $code) : '';
  1234. }
  1235. private function addDefaultParametersMethod(): string
  1236. {
  1237. if (!$this->container->getParameterBag()->all()) {
  1238. return '';
  1239. }
  1240. $php = [];
  1241. $dynamicPhp = [];
  1242. foreach ($this->container->getParameterBag()->all() as $key => $value) {
  1243. if ($key !== $resolvedKey = $this->container->resolveEnvPlaceholders($key)) {
  1244. throw new InvalidArgumentException(sprintf('Parameter name cannot use env parameters: "%s".', $resolvedKey));
  1245. }
  1246. $export = $this->exportParameters([$value]);
  1247. $export = explode('0 => ', substr(rtrim($export, " ]\n"), 2, -1), 2);
  1248. if (preg_match("/\\\$this->(?:getEnv\('(?:[-.\w]*+:)*+\w++'\)|targetDir\.'')/", $export[1])) {
  1249. $dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;', $export[0], $this->export($key), $export[1]);
  1250. } else {
  1251. $php[] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]);
  1252. }
  1253. }
  1254. $parameters = sprintf("[\n%s\n%s]", implode("\n", $php), str_repeat(' ', 8));
  1255. $code = <<<'EOF'
  1256. /**
  1257. * @return array|bool|float|int|string|null
  1258. */
  1259. public function getParameter(string $name)
  1260. {
  1261. if (isset($this->buildParameters[$name])) {
  1262. return $this->buildParameters[$name];
  1263. }
  1264. if (!(isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || \array_key_exists($name, $this->parameters))) {
  1265. throw new InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
  1266. }
  1267. if (isset($this->loadedDynamicParameters[$name])) {
  1268. return $this->loadedDynamicParameters[$name] ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
  1269. }
  1270. return $this->parameters[$name];
  1271. }
  1272. public function hasParameter(string $name): bool
  1273. {
  1274. if (isset($this->buildParameters[$name])) {
  1275. return true;
  1276. }
  1277. return isset($this->parameters[$name]) || isset($this->loadedDynamicParameters[$name]) || \array_key_exists($name, $this->parameters);
  1278. }
  1279. public function setParameter(string $name, $value): void
  1280. {
  1281. throw new LogicException('Impossible to call set() on a frozen ParameterBag.');
  1282. }
  1283. public function getParameterBag(): ParameterBagInterface
  1284. {
  1285. if (null === $this->parameterBag) {
  1286. $parameters = $this->parameters;
  1287. foreach ($this->loadedDynamicParameters as $name => $loaded) {
  1288. $parameters[$name] = $loaded ? $this->dynamicParameters[$name] : $this->getDynamicParameter($name);
  1289. }
  1290. foreach ($this->buildParameters as $name => $value) {
  1291. $parameters[$name] = $value;
  1292. }
  1293. $this->parameterBag = new FrozenParameterBag($parameters);
  1294. }
  1295. return $this->parameterBag;
  1296. }
  1297. EOF;
  1298. if (!$this->asFiles) {
  1299. $code = preg_replace('/^.*buildParameters.*\n.*\n.*\n\n?/m', '', $code);
  1300. }
  1301. if ($dynamicPhp) {
  1302. $loadedDynamicParameters = $this->exportParameters(array_combine(array_keys($dynamicPhp), array_fill(0, \count($dynamicPhp), false)), '', 8);
  1303. $getDynamicParameter = <<<'EOF'
  1304. switch ($name) {
  1305. %s
  1306. default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%%s" must be defined.', $name));
  1307. }
  1308. $this->loadedDynamicParameters[$name] = true;
  1309. return $this->dynamicParameters[$name] = $value;
  1310. EOF;
  1311. $getDynamicParameter = sprintf($getDynamicParameter, implode("\n", $dynamicPhp));
  1312. } else {
  1313. $loadedDynamicParameters = '[]';
  1314. $getDynamicParameter = str_repeat(' ', 8).'throw new InvalidArgumentException(sprintf(\'The dynamic parameter "%s" must be defined.\', $name));';
  1315. }
  1316. $code .= <<<EOF
  1317. private \$loadedDynamicParameters = {$loadedDynamicParameters};
  1318. private \$dynamicParameters = [];
  1319. private function getDynamicParameter(string \$name)
  1320. {
  1321. {$getDynamicParameter}
  1322. }
  1323. protected function getDefaultParameters(): array
  1324. {
  1325. return $parameters;
  1326. }
  1327. EOF;
  1328. return $code;
  1329. }
  1330. /**
  1331. * @throws InvalidArgumentException
  1332. */
  1333. private function exportParameters(array $parameters, string $path = '', int $indent = 12): string
  1334. {
  1335. $php = [];
  1336. foreach ($parameters as $key => $value) {
  1337. if (\is_array($value)) {
  1338. $value = $this->exportParameters($value, $path.'/'.$key, $indent + 4);
  1339. } elseif ($value instanceof ArgumentInterface) {
  1340. throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain special arguments. "%s" found in "%s".', get_debug_type($value), $path.'/'.$key));
  1341. } elseif ($value instanceof Variable) {
  1342. throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain variable references. Variable "%s" found in "%s".', $value, $path.'/'.$key));
  1343. } elseif ($value instanceof Definition) {
  1344. 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));
  1345. } elseif ($value instanceof Reference) {
  1346. 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));
  1347. } elseif ($value instanceof Expression) {
  1348. throw new InvalidArgumentException(sprintf('You cannot dump a container with parameters that contain expressions. Expression "%s" found in "%s".', $value, $path.'/'.$key));
  1349. } else {
  1350. $value = $this->export($value);
  1351. }
  1352. $php[] = sprintf('%s%s => %s,', str_repeat(' ', $indent), $this->export($key), $value);
  1353. }
  1354. return sprintf("[\n%s\n%s]", implode("\n", $php), str_repeat(' ', $indent - 4));
  1355. }
  1356. private function endClass(): string
  1357. {
  1358. if ($this->addThrow) {
  1359. return <<<'EOF'
  1360. protected function throw($message)
  1361. {
  1362. throw new RuntimeException($message);
  1363. }
  1364. }
  1365. EOF;
  1366. }
  1367. return <<<'EOF'
  1368. }
  1369. EOF;
  1370. }
  1371. private function wrapServiceConditionals($value, string $code): string
  1372. {
  1373. if (!$condition = $this->getServiceConditionals($value)) {
  1374. return $code;
  1375. }
  1376. // re-indent the wrapped code
  1377. $code = implode("\n", array_map(function ($line) { return $line ? ' '.$line : $line; }, explode("\n", $code)));
  1378. return sprintf(" if (%s) {\n%s }\n", $condition, $code);
  1379. }
  1380. private function getServiceConditionals($value): string
  1381. {
  1382. $conditions = [];
  1383. foreach (ContainerBuilder::getInitializedConditionals($value) as $service) {
  1384. if (!$this->container->hasDefinition($service)) {
  1385. return 'false';
  1386. }
  1387. $conditions[] = sprintf('isset($this->%s[%s])', $this->container->getDefinition($service)->isPublic() ? 'services' : 'privates', $this->doExport($service));
  1388. }
  1389. foreach (ContainerBuilder::getServiceConditionals($value) as $service) {
  1390. if ($this->container->hasDefinition($service) && !$this->container->getDefinition($service)->isPublic()) {
  1391. continue;
  1392. }
  1393. $conditions[] = sprintf('$this->has(%s)', $this->doExport($service));
  1394. }
  1395. if (!$conditions) {
  1396. return '';
  1397. }
  1398. return implode(' && ', $conditions);
  1399. }
  1400. private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null, array &$calls = [], bool $byConstructor = null): \SplObjectStorage
  1401. {
  1402. if (null === $definitions) {
  1403. $definitions = new \SplObjectStorage();
  1404. }
  1405. foreach ($arguments as $argument) {
  1406. if (\is_array($argument)) {
  1407. $this->getDefinitionsFromArguments($argument, $definitions, $calls, $byConstructor);
  1408. } elseif ($argument instanceof Reference) {
  1409. $id = (string) $argument;
  1410. while ($this->container->hasAlias($id)) {
  1411. $id = (string) $this->container->getAlias($id);
  1412. }
  1413. if (!isset($calls[$id])) {
  1414. $calls[$id] = [0, $argument->getInvalidBehavior(), $byConstructor];
  1415. } else {
  1416. $calls[$id][1] = min($calls[$id][1], $argument->getInvalidBehavior());
  1417. }
  1418. ++$calls[$id][0];
  1419. } elseif (!$argument instanceof Definition) {
  1420. // no-op
  1421. } elseif (isset($definitions[$argument])) {
  1422. $definitions[$argument] = 1 + $definitions[$argument];
  1423. } else {
  1424. $definitions[$argument] = 1;
  1425. $arguments = [$argument->getArguments(), $argument->getFactory()];
  1426. $this->getDefinitionsFromArguments($arguments, $definitions, $calls, null === $byConstructor || $byConstructor);
  1427. $arguments = [$argument->getProperties(), $argument->getMethodCalls(), $argument->getConfigurator()];
  1428. $this->getDefinitionsFromArguments($arguments, $definitions, $calls, null !== $byConstructor && $byConstructor);
  1429. }
  1430. }
  1431. return $definitions;
  1432. }
  1433. /**
  1434. * @throws RuntimeException
  1435. */
  1436. private function dumpValue($value, bool $interpolate = true): string
  1437. {
  1438. if (\is_array($value)) {
  1439. if ($value && $interpolate && false !== $param = array_search($value, $this->container->getParameterBag()->all(), true)) {
  1440. return $this->dumpValue("%$param%");
  1441. }
  1442. $code = [];
  1443. foreach ($value as $k => $v) {
  1444. $code[] = sprintf('%s => %s', $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate));
  1445. }
  1446. return sprintf('[%s]', implode(', ', $code));
  1447. } elseif ($value instanceof ArgumentInterface) {
  1448. $scope = [$this->definitionVariables, $this->referenceVariables];
  1449. $this->definitionVariables = $this->referenceVariables = null;
  1450. try {
  1451. if ($value instanceof ServiceClosureArgument) {
  1452. $value = $value->getValues()[0];
  1453. $code = $this->dumpValue($value, $interpolate);
  1454. $returnedType = '';
  1455. if ($value instanceof TypedReference) {
  1456. $returnedType = sprintf(': %s\%s', ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE >= $value->getInvalidBehavior() ? '' : '?', $value->getType());
  1457. }
  1458. $code = sprintf('return %s;', $code);
  1459. return sprintf("function ()%s {\n %s\n }", $returnedType, $code);
  1460. }
  1461. if ($value instanceof IteratorArgument) {
  1462. $operands = [0];
  1463. $code = [];
  1464. $code[] = 'new RewindableGenerator(function () {';
  1465. if (!$values = $value->getValues()) {
  1466. $code[] = ' return new \EmptyIterator();';
  1467. } else {
  1468. $countCode = [];
  1469. $countCode[] = 'function () {';
  1470. foreach ($values as $k => $v) {
  1471. ($c = $this->getServiceConditionals($v)) ? $operands[] = "(int) ($c)" : ++$operands[0];
  1472. $v = $this->wrapServiceConditionals($v, sprintf(" yield %s => %s;\n", $this->dumpValue($k, $interpolate), $this->dumpValue($v, $interpolate)));
  1473. foreach (explode("\n", $v) as $v) {
  1474. if ($v) {
  1475. $code[] = ' '.$v;
  1476. }
  1477. }
  1478. }
  1479. $countCode[] = sprintf(' return %s;', implode(' + ', $operands));
  1480. $countCode[] = ' }';
  1481. }
  1482. $code[] = sprintf(' }, %s)', \count($operands) > 1 ? implode("\n", $countCode) : $operands[0]);
  1483. return implode("\n", $code);
  1484. }
  1485. if ($value instanceof ServiceLocatorArgument) {
  1486. $serviceMap = '';
  1487. $serviceTypes = '';
  1488. foreach ($value->getValues() as $k => $v) {
  1489. if (!$v) {
  1490. continue;
  1491. }
  1492. $id = (string) $v;
  1493. while ($this->container->hasAlias($id)) {
  1494. $id = (string) $this->container->getAlias($id);
  1495. }
  1496. $definition = $this->container->getDefinition($id);
  1497. $load = !($definition->hasErrors() && $e = $definition->getErrors()) ? $this->asFiles && !$this->inlineFactories && !$this->isHotPath($definition) : reset($e);
  1498. $serviceMap .= sprintf("\n %s => [%s, %s, %s, %s],",
  1499. $this->export($k),
  1500. $this->export($definition->isShared() ? ($definition->isPublic() ? 'services' : 'privates') : false),
  1501. $this->doExport($id),
  1502. $this->export(ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE !== $v->getInvalidBehavior() && !\is_string($load) ? $this->generateMethodName($id) : null),
  1503. $this->export($load)
  1504. );
  1505. $serviceTypes .= sprintf("\n %s => %s,", $this->export($k), $this->export($v instanceof TypedReference ? $v->getType() : '?'));
  1506. $this->locatedIds[$id] = true;
  1507. }
  1508. $this->addGetService = true;
  1509. return sprintf('new \%s($this->getService, [%s%s], [%s%s])', ServiceLocator::class, $serviceMap, $serviceMap ? "\n " : '', $serviceTypes, $serviceTypes ? "\n " : '');
  1510. }
  1511. } finally {
  1512. [$this->definitionVariables, $this->referenceVariables] = $scope;
  1513. }
  1514. } elseif ($value instanceof Definition) {
  1515. if ($value->hasErrors() && $e = $value->getErrors()) {
  1516. $this->addThrow = true;
  1517. return sprintf('$this->throw(%s)', $this->export(reset($e)));
  1518. }
  1519. if (null !== $this->definitionVariables && $this->definitionVariables->contains($value)) {
  1520. return $this->dumpValue($this->definitionVariables[$value], $interpolate);
  1521. }
  1522. if ($value->getMethodCalls()) {
  1523. throw new RuntimeException('Cannot dump definitions which have method calls.');
  1524. }
  1525. if ($value->getProperties()) {
  1526. throw new RuntimeException('Cannot dump definitions which have properties.');
  1527. }
  1528. if (null !== $value->getConfigurator()) {
  1529. throw new RuntimeException('Cannot dump definitions which have a configurator.');
  1530. }
  1531. return $this->addNewInstance($value);
  1532. } elseif ($value instanceof Variable) {
  1533. return '$'.$value;
  1534. } elseif ($value instanceof Reference) {
  1535. $id = (string) $value;
  1536. while ($this->container->hasAlias($id)) {
  1537. $id = (string) $this->container->getAlias($id);
  1538. }
  1539. if (null !== $this->referenceVariables && isset($this->referenceVariables[$id])) {
  1540. return $this->dumpValue($this->referenceVariables[$id], $interpolate);
  1541. }
  1542. return $this->getServiceCall($id, $value);
  1543. } elseif ($value instanceof Expression) {
  1544. return $this->getExpressionLanguage()->compile((string) $value, ['this' => 'container']);
  1545. } elseif ($value instanceof Parameter) {
  1546. return $this->dumpParameter($value);
  1547. } elseif (true === $interpolate && \is_string($value)) {
  1548. if (preg_match('/^%([^%]+)%$/', $value, $match)) {
  1549. // we do this to deal with non string values (Boolean, integer, ...)
  1550. // the preg_replace_callback converts them to strings
  1551. return $this->dumpParameter($match[1]);
  1552. } else {
  1553. $replaceParameters = function ($match) {
  1554. return "'.".$this->dumpParameter($match[2]).".'";
  1555. };
  1556. $code = str_replace('%%', '%', preg_replace_callback('/(?<!%)(%)([^%]+)\1/', $replaceParameters, $this->export($value)));
  1557. return $code;
  1558. }
  1559. } elseif ($value instanceof AbstractArgument) {
  1560. throw new RuntimeException($value->getTextWithContext());
  1561. } elseif (\is_object($value) || \is_resource($value)) {
  1562. throw new RuntimeException('Unable to dump a service container if a parameter is an object or a resource.');
  1563. }
  1564. return $this->export($value);
  1565. }
  1566. /**
  1567. * Dumps a string to a literal (aka PHP Code) class value.
  1568. *
  1569. * @throws RuntimeException
  1570. */
  1571. private function dumpLiteralClass(string $class): string
  1572. {
  1573. if (false !== strpos($class, '$')) {
  1574. return sprintf('${($_ = %s) && false ?: "_"}', $class);
  1575. }
  1576. 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)) {
  1577. throw new RuntimeException(sprintf('Cannot dump definition because of invalid class name (%s).', $class ?: 'n/a'));
  1578. }
  1579. $class = substr(str_replace('\\\\', '\\', $class), 1, -1);
  1580. return 0 === strpos($class, '\\') ? $class : '\\'.$class;
  1581. }
  1582. private function dumpParameter(string $name): string
  1583. {
  1584. if ($this->container->hasParameter($name)) {
  1585. $value = $this->container->getParameter($name);
  1586. $dumpedValue = $this->dumpValue($value, false);
  1587. if (!$value || !\is_array($value)) {
  1588. return $dumpedValue;
  1589. }
  1590. if (!preg_match("/\\\$this->(?:getEnv\('(?:[-.\w]*+:)*+\w++'\)|targetDir\.'')/", $dumpedValue)) {
  1591. return sprintf('$this->parameters[%s]', $this->doExport($name));
  1592. }
  1593. }
  1594. return sprintf('$this->getParameter(%s)', $this->doExport($name));
  1595. }
  1596. private function getServiceCall(string $id, Reference $reference = null): string
  1597. {
  1598. while ($this->container->hasAlias($id)) {
  1599. $id = (string) $this->container->getAlias($id);
  1600. }
  1601. if ('service_container' === $id) {
  1602. return '$this';
  1603. }
  1604. if ($this->container->hasDefinition($id) && $definition = $this->container->getDefinition($id)) {
  1605. if ($definition->isSynthetic()) {
  1606. $code = sprintf('$this->get(%s%s)', $this->doExport($id), null !== $reference ? ', '.$reference->getInvalidBehavior() : '');
  1607. } elseif (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) {
  1608. $code = 'null';
  1609. if (!$definition->isShared()) {
  1610. return $code;
  1611. }
  1612. } elseif ($this->isTrivialInstance($definition)) {
  1613. if ($definition->hasErrors() && $e = $definition->getErrors()) {
  1614. $this->addThrow = true;
  1615. return sprintf('$this->throw(%s)', $this->export(reset($e)));
  1616. }
  1617. $code = $this->addNewInstance($definition, '', $id);
  1618. if ($definition->isShared() && !isset($this->singleUsePrivateIds[$id])) {
  1619. $code = sprintf('$this->%s[%s] = %s', $definition->isPublic() ? 'services' : 'privates', $this->doExport($id), $code);
  1620. }
  1621. $code = "($code)";
  1622. } else {
  1623. $code = $this->asFiles && !$this->inlineFactories && !$this->isHotPath($definition) ? "\$this->load('%s')" : '$this->%s()';
  1624. $code = sprintf($code, $this->generateMethodName($id));
  1625. if (!$definition->isShared()) {
  1626. $factory = sprintf('$this->factories%s[%s]', $definition->isPublic() ? '' : "['service_container']", $this->doExport($id));
  1627. $code = sprintf('(isset(%s) ? %1$s() : %s)', $factory, $code);
  1628. }
  1629. }
  1630. if ($definition->isShared() && !isset($this->singleUsePrivateIds[$id])) {
  1631. $code = sprintf('($this->%s[%s] ?? %s)', $definition->isPublic() ? 'services' : 'privates', $this->doExport($id), $code);
  1632. }
  1633. return $code;
  1634. }
  1635. if (null !== $reference && ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE === $reference->getInvalidBehavior()) {
  1636. return 'null';
  1637. }
  1638. if (null !== $reference && ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE < $reference->getInvalidBehavior()) {
  1639. $code = sprintf('$this->get(%s, /* ContainerInterface::NULL_ON_INVALID_REFERENCE */ %d)', $this->doExport($id), ContainerInterface::NULL_ON_INVALID_REFERENCE);
  1640. } else {
  1641. $code = sprintf('$this->get(%s)', $this->doExport($id));
  1642. }
  1643. return sprintf('($this->services[%s] ?? %s)', $this->doExport($id), $code);
  1644. }
  1645. /**
  1646. * Initializes the method names map to avoid conflicts with the Container methods.
  1647. */
  1648. private function initializeMethodNamesMap(string $class)
  1649. {
  1650. $this->serviceIdToMethodNameMap = [];
  1651. $this->usedMethodNames = [];
  1652. if ($reflectionClass = $this->container->getReflectionClass($class)) {
  1653. foreach ($reflectionClass->getMethods() as $method) {
  1654. $this->usedMethodNames[strtolower($method->getName())] = true;
  1655. }
  1656. }
  1657. }
  1658. /**
  1659. * @throws InvalidArgumentException
  1660. */
  1661. private function generateMethodName(string $id): string
  1662. {
  1663. if (isset($this->serviceIdToMethodNameMap[$id])) {
  1664. return $this->serviceIdToMethodNameMap[$id];
  1665. }
  1666. $i = strrpos($id, '\\');
  1667. $name = Container::camelize(false !== $i && isset($id[1 + $i]) ? substr($id, 1 + $i) : $id);
  1668. $name = preg_replace('/[^a-zA-Z0-9_\x7f-\xff]/', '', $name);
  1669. $methodName = 'get'.$name.'Service';
  1670. $suffix = 1;
  1671. while (isset($this->usedMethodNames[strtolower($methodName)])) {
  1672. ++$suffix;
  1673. $methodName = 'get'.$name.$suffix.'Service';
  1674. }
  1675. $this->serviceIdToMethodNameMap[$id] = $methodName;
  1676. $this->usedMethodNames[strtolower($methodName)] = true;
  1677. return $methodName;
  1678. }
  1679. private function getNextVariableName(): string
  1680. {
  1681. $firstChars = self::FIRST_CHARS;
  1682. $firstCharsLength = \strlen($firstChars);
  1683. $nonFirstChars = self::NON_FIRST_CHARS;
  1684. $nonFirstCharsLength = \strlen($nonFirstChars);
  1685. while (true) {
  1686. $name = '';
  1687. $i = $this->variableCount;
  1688. if ('' === $name) {
  1689. $name .= $firstChars[$i % $firstCharsLength];
  1690. $i = (int) ($i / $firstCharsLength);
  1691. }
  1692. while ($i > 0) {
  1693. --$i;
  1694. $name .= $nonFirstChars[$i % $nonFirstCharsLength];
  1695. $i = (int) ($i / $nonFirstCharsLength);
  1696. }
  1697. ++$this->variableCount;
  1698. // check that the name is not reserved
  1699. if (\in_array($name, $this->reservedVariables, true)) {
  1700. continue;
  1701. }
  1702. return $name;
  1703. }
  1704. }
  1705. private function getExpressionLanguage(): ExpressionLanguage
  1706. {
  1707. if (null === $this->expressionLanguage) {
  1708. if (!class_exists(\Symfony\Component\ExpressionLanguage\ExpressionLanguage::class)) {
  1709. throw new LogicException('Unable to use expressions as the Symfony ExpressionLanguage component is not installed.');
  1710. }
  1711. $providers = $this->container->getExpressionLanguageProviders();
  1712. $this->expressionLanguage = new ExpressionLanguage(null, $providers, function ($arg) {
  1713. $id = '""' === substr_replace($arg, '', 1, -1) ? stripcslashes(substr($arg, 1, -1)) : null;
  1714. if (null !== $id && ($this->container->hasAlias($id) || $this->container->hasDefinition($id))) {
  1715. return $this->getServiceCall($id);
  1716. }
  1717. return sprintf('$this->get(%s)', $arg);
  1718. });
  1719. if ($this->container->isTrackingResources()) {
  1720. foreach ($providers as $provider) {
  1721. $this->container->addObjectResource($provider);
  1722. }
  1723. }
  1724. }
  1725. return $this->expressionLanguage;
  1726. }
  1727. private function isHotPath(Definition $definition): bool
  1728. {
  1729. return $this->hotPathTag && $definition->hasTag($this->hotPathTag) && !$definition->isDeprecated();
  1730. }
  1731. private function isSingleUsePrivateNode(ServiceReferenceGraphNode $node): bool
  1732. {
  1733. if ($node->getValue()->isPublic()) {
  1734. return false;
  1735. }
  1736. $ids = [];
  1737. foreach ($node->getInEdges() as $edge) {
  1738. if (!$value = $edge->getSourceNode()->getValue()) {
  1739. continue;
  1740. }
  1741. if ($edge->isLazy() || !$value instanceof Definition || !$value->isShared()) {
  1742. return false;
  1743. }
  1744. $ids[$edge->getSourceNode()->getId()] = true;
  1745. }
  1746. return 1 === \count($ids);
  1747. }
  1748. /**
  1749. * @return mixed
  1750. */
  1751. private function export($value)
  1752. {
  1753. if (null !== $this->targetDirRegex && \is_string($value) && preg_match($this->targetDirRegex, $value, $matches, \PREG_OFFSET_CAPTURE)) {
  1754. $suffix = $matches[0][1] + \strlen($matches[0][0]);
  1755. $matches[0][1] += \strlen($matches[1][0]);
  1756. $prefix = $matches[0][1] ? $this->doExport(substr($value, 0, $matches[0][1]), true).'.' : '';
  1757. if ('\\' === \DIRECTORY_SEPARATOR && isset($value[$suffix])) {
  1758. $cookie = '\\'.random_int(100000, \PHP_INT_MAX);
  1759. $suffix = '.'.$this->doExport(str_replace('\\', $cookie, substr($value, $suffix)), true);
  1760. $suffix = str_replace('\\'.$cookie, "'.\\DIRECTORY_SEPARATOR.'", $suffix);
  1761. } else {
  1762. $suffix = isset($value[$suffix]) ? '.'.$this->doExport(substr($value, $suffix), true) : '';
  1763. }
  1764. $dirname = $this->asFiles ? '$this->containerDir' : '__DIR__';
  1765. $offset = 2 + $this->targetDirMaxMatches - \count($matches);
  1766. if (0 < $offset) {
  1767. $dirname = sprintf('\dirname(__DIR__, %d)', $offset + (int) $this->asFiles);
  1768. } elseif ($this->asFiles) {
  1769. $dirname = "\$this->targetDir.''"; // empty string concatenation on purpose
  1770. }
  1771. if ($prefix || $suffix) {
  1772. return sprintf('(%s%s%s)', $prefix, $dirname, $suffix);
  1773. }
  1774. return $dirname;
  1775. }
  1776. return $this->doExport($value, true);
  1777. }
  1778. /**
  1779. * @return mixed
  1780. */
  1781. private function doExport($value, bool $resolveEnv = false)
  1782. {
  1783. $shouldCacheValue = $resolveEnv && \is_string($value);
  1784. if ($shouldCacheValue && isset($this->exportedVariables[$value])) {
  1785. return $this->exportedVariables[$value];
  1786. }
  1787. if (\is_string($value) && false !== strpos($value, "\n")) {
  1788. $cleanParts = explode("\n", $value);
  1789. $cleanParts = array_map(function ($part) { return var_export($part, true); }, $cleanParts);
  1790. $export = implode('."\n".', $cleanParts);
  1791. } else {
  1792. $export = var_export($value, true);
  1793. }
  1794. if ($this->asFiles) {
  1795. if (false !== strpos($export, '$this')) {
  1796. $export = str_replace('$this', "$'.'this", $export);
  1797. }
  1798. if (false !== strpos($export, 'function () {')) {
  1799. $export = str_replace('function () {', "function ('.') {", $export);
  1800. }
  1801. }
  1802. if ($resolveEnv && "'" === $export[0] && $export !== $resolvedExport = $this->container->resolveEnvPlaceholders($export, "'.\$this->getEnv('string:%s').'")) {
  1803. $export = $resolvedExport;
  1804. if (".''" === substr($export, -3)) {
  1805. $export = substr($export, 0, -3);
  1806. if ("'" === $export[1]) {
  1807. $export = substr_replace($export, '', 18, 7);
  1808. }
  1809. }
  1810. if ("'" === $export[1]) {
  1811. $export = substr($export, 3);
  1812. }
  1813. }
  1814. if ($shouldCacheValue) {
  1815. $this->exportedVariables[$value] = $export;
  1816. }
  1817. return $export;
  1818. }
  1819. private function getAutoloadFile(): ?string
  1820. {
  1821. $file = null;
  1822. foreach (spl_autoload_functions() as $autoloader) {
  1823. if (!\is_array($autoloader)) {
  1824. continue;
  1825. }
  1826. if ($autoloader[0] instanceof DebugClassLoader || $autoloader[0] instanceof LegacyDebugClassLoader) {
  1827. $autoloader = $autoloader[0]->getClassLoader();
  1828. }
  1829. if (!\is_array($autoloader) || !$autoloader[0] instanceof ClassLoader || !$autoloader[0]->findFile(__CLASS__)) {
  1830. continue;
  1831. }
  1832. foreach (get_declared_classes() as $class) {
  1833. if (0 === strpos($class, 'ComposerAutoloaderInit') && $class::getLoader() === $autoloader[0]) {
  1834. $file = \dirname((new \ReflectionClass($class))->getFileName(), 2).'/autoload.php';
  1835. if (null !== $this->targetDirRegex && preg_match($this->targetDirRegex.'A', $file)) {
  1836. return $file;
  1837. }
  1838. }
  1839. }
  1840. }
  1841. return $file;
  1842. }
  1843. private function getClasses(Definition $definition, string $id): array
  1844. {
  1845. $classes = [];
  1846. while ($definition instanceof Definition) {
  1847. foreach ($definition->getTag($this->preloadTags[0]) as $tag) {
  1848. if (!isset($tag['class'])) {
  1849. throw new InvalidArgumentException(sprintf('Missing attribute "class" on tag "%s" for service "%s".', $this->preloadTags[0], $id));
  1850. }
  1851. $classes[] = trim($tag['class'], '\\');
  1852. }
  1853. $classes[] = trim($definition->getClass(), '\\');
  1854. $factory = $definition->getFactory();
  1855. if (!\is_array($factory)) {
  1856. $factory = [$factory];
  1857. }
  1858. if (\is_string($factory[0])) {
  1859. if (false !== $i = strrpos($factory[0], '::')) {
  1860. $factory[0] = substr($factory[0], 0, $i);
  1861. }
  1862. $classes[] = trim($factory[0], '\\');
  1863. }
  1864. $definition = $factory[0];
  1865. }
  1866. return array_filter($classes);
  1867. }
  1868. }