YamlFileLoader.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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\Loader;
  11. use Symfony\Component\DependencyInjection\Alias;
  12. use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
  13. use Symfony\Component\DependencyInjection\Argument\BoundArgument;
  14. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  15. use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
  16. use Symfony\Component\DependencyInjection\Argument\ServiceLocatorArgument;
  17. use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
  18. use Symfony\Component\DependencyInjection\ChildDefinition;
  19. use Symfony\Component\DependencyInjection\ContainerBuilder;
  20. use Symfony\Component\DependencyInjection\ContainerInterface;
  21. use Symfony\Component\DependencyInjection\Definition;
  22. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  23. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  24. use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
  25. use Symfony\Component\DependencyInjection\Reference;
  26. use Symfony\Component\ExpressionLanguage\Expression;
  27. use Symfony\Component\Yaml\Exception\ParseException;
  28. use Symfony\Component\Yaml\Parser as YamlParser;
  29. use Symfony\Component\Yaml\Tag\TaggedValue;
  30. use Symfony\Component\Yaml\Yaml;
  31. /**
  32. * YamlFileLoader loads YAML files service definitions.
  33. *
  34. * @author Fabien Potencier <fabien@symfony.com>
  35. */
  36. class YamlFileLoader extends FileLoader
  37. {
  38. private const SERVICE_KEYWORDS = [
  39. 'alias' => 'alias',
  40. 'parent' => 'parent',
  41. 'class' => 'class',
  42. 'shared' => 'shared',
  43. 'synthetic' => 'synthetic',
  44. 'lazy' => 'lazy',
  45. 'public' => 'public',
  46. 'abstract' => 'abstract',
  47. 'deprecated' => 'deprecated',
  48. 'factory' => 'factory',
  49. 'file' => 'file',
  50. 'arguments' => 'arguments',
  51. 'properties' => 'properties',
  52. 'configurator' => 'configurator',
  53. 'calls' => 'calls',
  54. 'tags' => 'tags',
  55. 'decorates' => 'decorates',
  56. 'decoration_inner_name' => 'decoration_inner_name',
  57. 'decoration_priority' => 'decoration_priority',
  58. 'decoration_on_invalid' => 'decoration_on_invalid',
  59. 'autowire' => 'autowire',
  60. 'autoconfigure' => 'autoconfigure',
  61. 'bind' => 'bind',
  62. ];
  63. private const PROTOTYPE_KEYWORDS = [
  64. 'resource' => 'resource',
  65. 'namespace' => 'namespace',
  66. 'exclude' => 'exclude',
  67. 'parent' => 'parent',
  68. 'shared' => 'shared',
  69. 'lazy' => 'lazy',
  70. 'public' => 'public',
  71. 'abstract' => 'abstract',
  72. 'deprecated' => 'deprecated',
  73. 'factory' => 'factory',
  74. 'arguments' => 'arguments',
  75. 'properties' => 'properties',
  76. 'configurator' => 'configurator',
  77. 'calls' => 'calls',
  78. 'tags' => 'tags',
  79. 'autowire' => 'autowire',
  80. 'autoconfigure' => 'autoconfigure',
  81. 'bind' => 'bind',
  82. ];
  83. private const INSTANCEOF_KEYWORDS = [
  84. 'shared' => 'shared',
  85. 'lazy' => 'lazy',
  86. 'public' => 'public',
  87. 'properties' => 'properties',
  88. 'configurator' => 'configurator',
  89. 'calls' => 'calls',
  90. 'tags' => 'tags',
  91. 'autowire' => 'autowire',
  92. 'bind' => 'bind',
  93. ];
  94. private const DEFAULTS_KEYWORDS = [
  95. 'public' => 'public',
  96. 'tags' => 'tags',
  97. 'autowire' => 'autowire',
  98. 'autoconfigure' => 'autoconfigure',
  99. 'bind' => 'bind',
  100. ];
  101. private $yamlParser;
  102. private $anonymousServicesCount;
  103. private $anonymousServicesSuffix;
  104. protected $autoRegisterAliasesForSinglyImplementedInterfaces = false;
  105. /**
  106. * {@inheritdoc}
  107. */
  108. public function load($resource, $type = null)
  109. {
  110. $path = $this->locator->locate($resource);
  111. $content = $this->loadFile($path);
  112. $this->container->fileExists($path);
  113. // empty file
  114. if (null === $content) {
  115. return;
  116. }
  117. // imports
  118. $this->parseImports($content, $path);
  119. // parameters
  120. if (isset($content['parameters'])) {
  121. if (!\is_array($content['parameters'])) {
  122. throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in "%s". Check your YAML syntax.', $path));
  123. }
  124. foreach ($content['parameters'] as $key => $value) {
  125. $this->container->setParameter($key, $this->resolveServices($value, $path, true));
  126. }
  127. }
  128. // extensions
  129. $this->loadFromExtensions($content);
  130. // services
  131. $this->anonymousServicesCount = 0;
  132. $this->anonymousServicesSuffix = '~'.ContainerBuilder::hash($path);
  133. $this->setCurrentDir(\dirname($path));
  134. try {
  135. $this->parseDefinitions($content, $path);
  136. } finally {
  137. $this->instanceof = [];
  138. $this->registerAliasesForSinglyImplementedInterfaces();
  139. }
  140. }
  141. /**
  142. * {@inheritdoc}
  143. */
  144. public function supports($resource, $type = null)
  145. {
  146. if (!\is_string($resource)) {
  147. return false;
  148. }
  149. if (null === $type && \in_array(pathinfo($resource, \PATHINFO_EXTENSION), ['yaml', 'yml'], true)) {
  150. return true;
  151. }
  152. return \in_array($type, ['yaml', 'yml'], true);
  153. }
  154. private function parseImports(array $content, string $file)
  155. {
  156. if (!isset($content['imports'])) {
  157. return;
  158. }
  159. if (!\is_array($content['imports'])) {
  160. throw new InvalidArgumentException(sprintf('The "imports" key should contain an array in "%s". Check your YAML syntax.', $file));
  161. }
  162. $defaultDirectory = \dirname($file);
  163. foreach ($content['imports'] as $import) {
  164. if (!\is_array($import)) {
  165. $import = ['resource' => $import];
  166. }
  167. if (!isset($import['resource'])) {
  168. throw new InvalidArgumentException(sprintf('An import should provide a resource in "%s". Check your YAML syntax.', $file));
  169. }
  170. $this->setCurrentDir($defaultDirectory);
  171. $this->import($import['resource'], $import['type'] ?? null, $import['ignore_errors'] ?? false, $file);
  172. }
  173. }
  174. private function parseDefinitions(array $content, string $file)
  175. {
  176. if (!isset($content['services'])) {
  177. return;
  178. }
  179. if (!\is_array($content['services'])) {
  180. throw new InvalidArgumentException(sprintf('The "services" key should contain an array in "%s". Check your YAML syntax.', $file));
  181. }
  182. if (\array_key_exists('_instanceof', $content['services'])) {
  183. $instanceof = $content['services']['_instanceof'];
  184. unset($content['services']['_instanceof']);
  185. if (!\is_array($instanceof)) {
  186. throw new InvalidArgumentException(sprintf('Service "_instanceof" key must be an array, "%s" given in "%s".', \gettype($instanceof), $file));
  187. }
  188. $this->instanceof = [];
  189. $this->isLoadingInstanceof = true;
  190. foreach ($instanceof as $id => $service) {
  191. if (!$service || !\is_array($service)) {
  192. throw new InvalidArgumentException(sprintf('Type definition "%s" must be a non-empty array within "_instanceof" in "%s". Check your YAML syntax.', $id, $file));
  193. }
  194. if (\is_string($service) && 0 === strpos($service, '@')) {
  195. throw new InvalidArgumentException(sprintf('Type definition "%s" cannot be an alias within "_instanceof" in "%s". Check your YAML syntax.', $id, $file));
  196. }
  197. $this->parseDefinition($id, $service, $file, []);
  198. }
  199. }
  200. $this->isLoadingInstanceof = false;
  201. $defaults = $this->parseDefaults($content, $file);
  202. foreach ($content['services'] as $id => $service) {
  203. $this->parseDefinition($id, $service, $file, $defaults);
  204. }
  205. }
  206. /**
  207. * @throws InvalidArgumentException
  208. */
  209. private function parseDefaults(array &$content, string $file): array
  210. {
  211. if (!\array_key_exists('_defaults', $content['services'])) {
  212. return [];
  213. }
  214. $defaults = $content['services']['_defaults'];
  215. unset($content['services']['_defaults']);
  216. if (!\is_array($defaults)) {
  217. throw new InvalidArgumentException(sprintf('Service "_defaults" key must be an array, "%s" given in "%s".', \gettype($defaults), $file));
  218. }
  219. foreach ($defaults as $key => $default) {
  220. if (!isset(self::DEFAULTS_KEYWORDS[$key])) {
  221. throw new InvalidArgumentException(sprintf('The configuration key "%s" cannot be used to define a default value in "%s". Allowed keys are "%s".', $key, $file, implode('", "', self::DEFAULTS_KEYWORDS)));
  222. }
  223. }
  224. if (isset($defaults['tags'])) {
  225. if (!\is_array($tags = $defaults['tags'])) {
  226. throw new InvalidArgumentException(sprintf('Parameter "tags" in "_defaults" must be an array in "%s". Check your YAML syntax.', $file));
  227. }
  228. foreach ($tags as $tag) {
  229. if (!\is_array($tag)) {
  230. $tag = ['name' => $tag];
  231. }
  232. if (!isset($tag['name'])) {
  233. throw new InvalidArgumentException(sprintf('A "tags" entry in "_defaults" is missing a "name" key in "%s".', $file));
  234. }
  235. $name = $tag['name'];
  236. unset($tag['name']);
  237. if (!\is_string($name) || '' === $name) {
  238. throw new InvalidArgumentException(sprintf('The tag name in "_defaults" must be a non-empty string in "%s".', $file));
  239. }
  240. foreach ($tag as $attribute => $value) {
  241. if (!is_scalar($value) && null !== $value) {
  242. throw new InvalidArgumentException(sprintf('Tag "%s", attribute "%s" in "_defaults" must be of a scalar-type in "%s". Check your YAML syntax.', $name, $attribute, $file));
  243. }
  244. }
  245. }
  246. }
  247. if (isset($defaults['bind'])) {
  248. if (!\is_array($defaults['bind'])) {
  249. throw new InvalidArgumentException(sprintf('Parameter "bind" in "_defaults" must be an array in "%s". Check your YAML syntax.', $file));
  250. }
  251. foreach ($this->resolveServices($defaults['bind'], $file) as $argument => $value) {
  252. $defaults['bind'][$argument] = new BoundArgument($value, true, BoundArgument::DEFAULTS_BINDING, $file);
  253. }
  254. }
  255. return $defaults;
  256. }
  257. private function isUsingShortSyntax(array $service): bool
  258. {
  259. foreach ($service as $key => $value) {
  260. if (\is_string($key) && ('' === $key || ('$' !== $key[0] && false === strpos($key, '\\')))) {
  261. return false;
  262. }
  263. }
  264. return true;
  265. }
  266. /**
  267. * Parses a definition.
  268. *
  269. * @param array|string|null $service
  270. *
  271. * @throws InvalidArgumentException When tags are invalid
  272. */
  273. private function parseDefinition(string $id, $service, string $file, array $defaults)
  274. {
  275. if (preg_match('/^_[a-zA-Z0-9_]*$/', $id)) {
  276. throw new InvalidArgumentException(sprintf('Service names that start with an underscore are reserved. Rename the "%s" service or define it in XML instead.', $id));
  277. }
  278. if (\is_string($service) && 0 === strpos($service, '@')) {
  279. $this->container->setAlias($id, $alias = new Alias(substr($service, 1)));
  280. if (isset($defaults['public'])) {
  281. $alias->setPublic($defaults['public']);
  282. }
  283. return;
  284. }
  285. if (\is_array($service) && $this->isUsingShortSyntax($service)) {
  286. $service = ['arguments' => $service];
  287. }
  288. if (null === $service) {
  289. $service = [];
  290. }
  291. if (!\is_array($service)) {
  292. throw new InvalidArgumentException(sprintf('A service definition must be an array or a string starting with "@" but "%s" found for service "%s" in "%s". Check your YAML syntax.', \gettype($service), $id, $file));
  293. }
  294. $this->checkDefinition($id, $service, $file);
  295. if (isset($service['alias'])) {
  296. $this->container->setAlias($id, $alias = new Alias($service['alias']));
  297. if (isset($service['public'])) {
  298. $alias->setPublic($service['public']);
  299. } elseif (isset($defaults['public'])) {
  300. $alias->setPublic($defaults['public']);
  301. }
  302. foreach ($service as $key => $value) {
  303. if (!\in_array($key, ['alias', 'public', 'deprecated'])) {
  304. throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported for the service "%s" which is defined as an alias in "%s". Allowed configuration keys for service aliases are "alias", "public" and "deprecated".', $key, $id, $file));
  305. }
  306. if ('deprecated' === $key) {
  307. $alias->setDeprecated(true, $value);
  308. }
  309. }
  310. return;
  311. }
  312. if ($this->isLoadingInstanceof) {
  313. $definition = new ChildDefinition('');
  314. } elseif (isset($service['parent'])) {
  315. if (!empty($this->instanceof)) {
  316. throw new InvalidArgumentException(sprintf('The service "%s" cannot use the "parent" option in the same file where "_instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.', $id));
  317. }
  318. foreach ($defaults as $k => $v) {
  319. if ('tags' === $k) {
  320. // since tags are never inherited from parents, there is no confusion
  321. // thus we can safely add them as defaults to ChildDefinition
  322. continue;
  323. }
  324. if ('bind' === $k) {
  325. throw new InvalidArgumentException(sprintf('Attribute "bind" on service "%s" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file.', $id));
  326. }
  327. if (!isset($service[$k])) {
  328. throw new InvalidArgumentException(sprintf('Attribute "%s" on service "%s" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.', $k, $id));
  329. }
  330. }
  331. if ('' !== $service['parent'] && '@' === $service['parent'][0]) {
  332. throw new InvalidArgumentException(sprintf('The value of the "parent" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $id, $service['parent'], substr($service['parent'], 1)));
  333. }
  334. $definition = new ChildDefinition($service['parent']);
  335. } else {
  336. $definition = new Definition();
  337. if (isset($defaults['public'])) {
  338. $definition->setPublic($defaults['public']);
  339. }
  340. if (isset($defaults['autowire'])) {
  341. $definition->setAutowired($defaults['autowire']);
  342. }
  343. if (isset($defaults['autoconfigure'])) {
  344. $definition->setAutoconfigured($defaults['autoconfigure']);
  345. }
  346. $definition->setChanges([]);
  347. }
  348. if (isset($service['class'])) {
  349. $definition->setClass($service['class']);
  350. }
  351. if (isset($service['shared'])) {
  352. $definition->setShared($service['shared']);
  353. }
  354. if (isset($service['synthetic'])) {
  355. $definition->setSynthetic($service['synthetic']);
  356. }
  357. if (isset($service['lazy'])) {
  358. $definition->setLazy((bool) $service['lazy']);
  359. if (\is_string($service['lazy'])) {
  360. $definition->addTag('proxy', ['interface' => $service['lazy']]);
  361. }
  362. }
  363. if (isset($service['public'])) {
  364. $definition->setPublic($service['public']);
  365. }
  366. if (isset($service['abstract'])) {
  367. $definition->setAbstract($service['abstract']);
  368. }
  369. if (\array_key_exists('deprecated', $service)) {
  370. $definition->setDeprecated(true, $service['deprecated']);
  371. }
  372. if (isset($service['factory'])) {
  373. $definition->setFactory($this->parseCallable($service['factory'], 'factory', $id, $file));
  374. }
  375. if (isset($service['file'])) {
  376. $definition->setFile($service['file']);
  377. }
  378. if (isset($service['arguments'])) {
  379. $definition->setArguments($this->resolveServices($service['arguments'], $file));
  380. }
  381. if (isset($service['properties'])) {
  382. $definition->setProperties($this->resolveServices($service['properties'], $file));
  383. }
  384. if (isset($service['configurator'])) {
  385. $definition->setConfigurator($this->parseCallable($service['configurator'], 'configurator', $id, $file));
  386. }
  387. if (isset($service['calls'])) {
  388. if (!\is_array($service['calls'])) {
  389. throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  390. }
  391. foreach ($service['calls'] as $k => $call) {
  392. if (!\is_array($call) && (!\is_string($k) || !$call instanceof TaggedValue)) {
  393. throw new InvalidArgumentException(sprintf('Invalid method call for service "%s": expected map or array, "%s" given in "%s".', $id, $call instanceof TaggedValue ? '!'.$call->getTag() : \gettype($call), $file));
  394. }
  395. if (\is_string($k)) {
  396. throw new InvalidArgumentException(sprintf('Invalid method call for service "%s", did you forgot a leading dash before "%s: ..." in "%s"?', $id, $k, $file));
  397. }
  398. if (isset($call['method']) && \is_string($call['method'])) {
  399. $method = $call['method'];
  400. $args = $call['arguments'] ?? [];
  401. $returnsClone = $call['returns_clone'] ?? false;
  402. } else {
  403. if (1 === \count($call) && \is_string(key($call))) {
  404. $method = key($call);
  405. $args = $call[$method];
  406. if ($args instanceof TaggedValue) {
  407. if ('returns_clone' !== $args->getTag()) {
  408. throw new InvalidArgumentException(sprintf('Unsupported tag "!%s", did you mean "!returns_clone" for service "%s" in "%s"?', $args->getTag(), $id, $file));
  409. }
  410. $returnsClone = true;
  411. $args = $args->getValue();
  412. } else {
  413. $returnsClone = false;
  414. }
  415. } elseif (empty($call[0])) {
  416. throw new InvalidArgumentException(sprintf('Invalid call for service "%s": the method must be defined as the first index of an array or as the only key of a map in "%s".', $id, $file));
  417. } else {
  418. $method = $call[0];
  419. $args = $call[1] ?? [];
  420. $returnsClone = $call[2] ?? false;
  421. }
  422. }
  423. if (!\is_array($args)) {
  424. throw new InvalidArgumentException(sprintf('The second parameter for function call "%s" must be an array of its arguments for service "%s" in "%s". Check your YAML syntax.', $method, $id, $file));
  425. }
  426. $args = $this->resolveServices($args, $file);
  427. $definition->addMethodCall($method, $args, $returnsClone);
  428. }
  429. }
  430. $tags = $service['tags'] ?? [];
  431. if (!\is_array($tags)) {
  432. throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  433. }
  434. if (isset($defaults['tags'])) {
  435. $tags = array_merge($tags, $defaults['tags']);
  436. }
  437. foreach ($tags as $tag) {
  438. if (!\is_array($tag)) {
  439. $tag = ['name' => $tag];
  440. }
  441. if (!isset($tag['name'])) {
  442. throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in "%s".', $id, $file));
  443. }
  444. $name = $tag['name'];
  445. unset($tag['name']);
  446. if (!\is_string($name) || '' === $name) {
  447. throw new InvalidArgumentException(sprintf('The tag name for service "%s" in "%s" must be a non-empty string.', $id, $file));
  448. }
  449. foreach ($tag as $attribute => $value) {
  450. if (!is_scalar($value) && null !== $value) {
  451. throw new InvalidArgumentException(sprintf('A "tags" attribute must be of a scalar-type for service "%s", tag "%s", attribute "%s" in "%s". Check your YAML syntax.', $id, $name, $attribute, $file));
  452. }
  453. }
  454. $definition->addTag($name, $tag);
  455. }
  456. if (null !== $decorates = $service['decorates'] ?? null) {
  457. if ('' !== $decorates && '@' === $decorates[0]) {
  458. throw new InvalidArgumentException(sprintf('The value of the "decorates" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s").', $id, $service['decorates'], substr($decorates, 1)));
  459. }
  460. $decorationOnInvalid = \array_key_exists('decoration_on_invalid', $service) ? $service['decoration_on_invalid'] : 'exception';
  461. if ('exception' === $decorationOnInvalid) {
  462. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  463. } elseif ('ignore' === $decorationOnInvalid) {
  464. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  465. } elseif (null === $decorationOnInvalid) {
  466. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  467. } elseif ('null' === $decorationOnInvalid) {
  468. throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration_on_invalid" on service "%s". Did you mean null (without quotes) in "%s"?', $decorationOnInvalid, $id, $file));
  469. } else {
  470. throw new InvalidArgumentException(sprintf('Invalid value "%s" for attribute "decoration_on_invalid" on service "%s". Did you mean "exception", "ignore" or null in "%s"?', $decorationOnInvalid, $id, $file));
  471. }
  472. $renameId = $service['decoration_inner_name'] ?? null;
  473. $priority = $service['decoration_priority'] ?? 0;
  474. $definition->setDecoratedService($decorates, $renameId, $priority, $invalidBehavior);
  475. }
  476. if (isset($service['autowire'])) {
  477. $definition->setAutowired($service['autowire']);
  478. }
  479. if (isset($defaults['bind']) || isset($service['bind'])) {
  480. // deep clone, to avoid multiple process of the same instance in the passes
  481. $bindings = isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : [];
  482. if (isset($service['bind'])) {
  483. if (!\is_array($service['bind'])) {
  484. throw new InvalidArgumentException(sprintf('Parameter "bind" must be an array for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  485. }
  486. $bindings = array_merge($bindings, $this->resolveServices($service['bind'], $file));
  487. $bindingType = $this->isLoadingInstanceof ? BoundArgument::INSTANCEOF_BINDING : BoundArgument::SERVICE_BINDING;
  488. foreach ($bindings as $argument => $value) {
  489. if (!$value instanceof BoundArgument) {
  490. $bindings[$argument] = new BoundArgument($value, true, $bindingType, $file);
  491. }
  492. }
  493. }
  494. $definition->setBindings($bindings);
  495. }
  496. if (isset($service['autoconfigure'])) {
  497. if (!$definition instanceof ChildDefinition) {
  498. $definition->setAutoconfigured($service['autoconfigure']);
  499. } elseif ($service['autoconfigure']) {
  500. throw new InvalidArgumentException(sprintf('The service "%s" cannot have a "parent" and also have "autoconfigure". Try setting "autoconfigure: false" for the service.', $id));
  501. }
  502. }
  503. if (\array_key_exists('namespace', $service) && !\array_key_exists('resource', $service)) {
  504. throw new InvalidArgumentException(sprintf('A "resource" attribute must be set when the "namespace" attribute is set for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  505. }
  506. if (\array_key_exists('resource', $service)) {
  507. if (!\is_string($service['resource'])) {
  508. throw new InvalidArgumentException(sprintf('A "resource" attribute must be of type string for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  509. }
  510. $exclude = $service['exclude'] ?? null;
  511. $namespace = $service['namespace'] ?? $id;
  512. $this->registerClasses($definition, $namespace, $service['resource'], $exclude);
  513. } else {
  514. $this->setDefinition($id, $definition);
  515. }
  516. }
  517. /**
  518. * Parses a callable.
  519. *
  520. * @param string|array $callable A callable reference
  521. *
  522. * @throws InvalidArgumentException When errors occur
  523. *
  524. * @return string|array|Reference A parsed callable
  525. */
  526. private function parseCallable($callable, string $parameter, string $id, string $file)
  527. {
  528. if (\is_string($callable)) {
  529. if ('' !== $callable && '@' === $callable[0]) {
  530. if (false === strpos($callable, ':')) {
  531. return [$this->resolveServices($callable, $file), '__invoke'];
  532. }
  533. throw new InvalidArgumentException(sprintf('The value of the "%s" option for the "%s" service must be the id of the service without the "@" prefix (replace "%s" with "%s" in "%s").', $parameter, $id, $callable, substr($callable, 1), $file));
  534. }
  535. if (false !== strpos($callable, ':') && false === strpos($callable, '::')) {
  536. $parts = explode(':', $callable);
  537. @trigger_error(sprintf('Using short %s syntax for service "%s" is deprecated since Symfony 4.4, use "[\'@%s\', \'%s\']" instead.', $parameter, $id, ...$parts), \E_USER_DEPRECATED);
  538. return [$this->resolveServices('@'.$parts[0], $file), $parts[1]];
  539. }
  540. return $callable;
  541. }
  542. if (\is_array($callable)) {
  543. if (isset($callable[0]) && isset($callable[1])) {
  544. return [$this->resolveServices($callable[0], $file), $callable[1]];
  545. }
  546. if ('factory' === $parameter && isset($callable[1]) && null === $callable[0]) {
  547. return $callable;
  548. }
  549. throw new InvalidArgumentException(sprintf('Parameter "%s" must contain an array with two elements for service "%s" in "%s". Check your YAML syntax.', $parameter, $id, $file));
  550. }
  551. throw new InvalidArgumentException(sprintf('Parameter "%s" must be a string or an array for service "%s" in "%s". Check your YAML syntax.', $parameter, $id, $file));
  552. }
  553. /**
  554. * Loads a YAML file.
  555. *
  556. * @param string $file
  557. *
  558. * @return array The file content
  559. *
  560. * @throws InvalidArgumentException when the given file is not a local file or when it does not exist
  561. */
  562. protected function loadFile($file)
  563. {
  564. if (!class_exists(\Symfony\Component\Yaml\Parser::class)) {
  565. throw new RuntimeException('Unable to load YAML config files as the Symfony Yaml Component is not installed.');
  566. }
  567. if (!stream_is_local($file)) {
  568. throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
  569. }
  570. if (!file_exists($file)) {
  571. throw new InvalidArgumentException(sprintf('The file "%s" does not exist.', $file));
  572. }
  573. if (null === $this->yamlParser) {
  574. $this->yamlParser = new YamlParser();
  575. }
  576. try {
  577. $configuration = $this->yamlParser->parseFile($file, Yaml::PARSE_CONSTANT | Yaml::PARSE_CUSTOM_TAGS);
  578. } catch (ParseException $e) {
  579. throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML: ', $file).$e->getMessage(), 0, $e);
  580. }
  581. return $this->validate($configuration, $file);
  582. }
  583. /**
  584. * Validates a YAML file.
  585. *
  586. * @throws InvalidArgumentException When service file is not valid
  587. */
  588. private function validate($content, string $file): ?array
  589. {
  590. if (null === $content) {
  591. return $content;
  592. }
  593. if (!\is_array($content)) {
  594. throw new InvalidArgumentException(sprintf('The service file "%s" is not valid. It should contain an array. Check your YAML syntax.', $file));
  595. }
  596. foreach ($content as $namespace => $data) {
  597. if (\in_array($namespace, ['imports', 'parameters', 'services'])) {
  598. continue;
  599. }
  600. if (!$this->container->hasExtension($namespace)) {
  601. $extensionNamespaces = array_filter(array_map(function (ExtensionInterface $ext) { return $ext->getAlias(); }, $this->container->getExtensions()));
  602. throw new InvalidArgumentException(sprintf('There is no extension able to load the configuration for "%s" (in "%s"). Looked for namespace "%s", found "%s".', $namespace, $file, $namespace, $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'));
  603. }
  604. }
  605. return $content;
  606. }
  607. /**
  608. * Resolves services.
  609. *
  610. * @return array|string|Reference|ArgumentInterface
  611. */
  612. private function resolveServices($value, string $file, bool $isParameter = false)
  613. {
  614. if ($value instanceof TaggedValue) {
  615. $argument = $value->getValue();
  616. if ('iterator' === $value->getTag()) {
  617. if (!\is_array($argument)) {
  618. throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts sequences in "%s".', $file));
  619. }
  620. $argument = $this->resolveServices($argument, $file, $isParameter);
  621. try {
  622. return new IteratorArgument($argument);
  623. } catch (InvalidArgumentException $e) {
  624. throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts arrays of "@service" references in "%s".', $file));
  625. }
  626. }
  627. if ('service_closure' === $value->getTag()) {
  628. $argument = $this->resolveServices($argument, $file, $isParameter);
  629. if (!$argument instanceof Reference) {
  630. throw new InvalidArgumentException(sprintf('"!service_closure" tag only accepts service references in "%s".', $file));
  631. }
  632. return new ServiceClosureArgument($argument);
  633. }
  634. if ('service_locator' === $value->getTag()) {
  635. if (!\is_array($argument)) {
  636. throw new InvalidArgumentException(sprintf('"!service_locator" tag only accepts maps in "%s".', $file));
  637. }
  638. $argument = $this->resolveServices($argument, $file, $isParameter);
  639. try {
  640. return new ServiceLocatorArgument($argument);
  641. } catch (InvalidArgumentException $e) {
  642. throw new InvalidArgumentException(sprintf('"!service_locator" tag only accepts maps of "@service" references in "%s".', $file));
  643. }
  644. }
  645. if (\in_array($value->getTag(), ['tagged', 'tagged_iterator', 'tagged_locator'], true)) {
  646. $forLocator = 'tagged_locator' === $value->getTag();
  647. if (\is_array($argument) && isset($argument['tag']) && $argument['tag']) {
  648. if ($diff = array_diff(array_keys($argument), ['tag', 'index_by', 'default_index_method', 'default_priority_method'])) {
  649. throw new InvalidArgumentException(sprintf('"!%s" tag contains unsupported key "%s"; supported ones are "tag", "index_by", "default_index_method", and "default_priority_method".', $value->getTag(), implode('", "', $diff)));
  650. }
  651. $argument = new TaggedIteratorArgument($argument['tag'], $argument['index_by'] ?? null, $argument['default_index_method'] ?? null, $forLocator, $argument['default_priority_method'] ?? null);
  652. } elseif (\is_string($argument) && $argument) {
  653. $argument = new TaggedIteratorArgument($argument, null, null, $forLocator);
  654. } else {
  655. throw new InvalidArgumentException(sprintf('"!%s" tags only accept a non empty string or an array with a key "tag" in "%s".', $value->getTag(), $file));
  656. }
  657. if ($forLocator) {
  658. $argument = new ServiceLocatorArgument($argument);
  659. }
  660. return $argument;
  661. }
  662. if ('service' === $value->getTag()) {
  663. if ($isParameter) {
  664. throw new InvalidArgumentException(sprintf('Using an anonymous service in a parameter is not allowed in "%s".', $file));
  665. }
  666. $isLoadingInstanceof = $this->isLoadingInstanceof;
  667. $this->isLoadingInstanceof = false;
  668. $instanceof = $this->instanceof;
  669. $this->instanceof = [];
  670. $id = sprintf('.%d_%s', ++$this->anonymousServicesCount, preg_replace('/^.*\\\\/', '', $argument['class'] ?? '').$this->anonymousServicesSuffix);
  671. $this->parseDefinition($id, $argument, $file, []);
  672. if (!$this->container->hasDefinition($id)) {
  673. throw new InvalidArgumentException(sprintf('Creating an alias using the tag "!service" is not allowed in "%s".', $file));
  674. }
  675. $this->container->getDefinition($id)->setPublic(false);
  676. $this->isLoadingInstanceof = $isLoadingInstanceof;
  677. $this->instanceof = $instanceof;
  678. return new Reference($id);
  679. }
  680. throw new InvalidArgumentException(sprintf('Unsupported tag "!%s".', $value->getTag()));
  681. }
  682. if (\is_array($value)) {
  683. foreach ($value as $k => $v) {
  684. $value[$k] = $this->resolveServices($v, $file, $isParameter);
  685. }
  686. } elseif (\is_string($value) && 0 === strpos($value, '@=')) {
  687. if (!class_exists(Expression::class)) {
  688. throw new \LogicException('The "@=" expression syntax cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
  689. }
  690. return new Expression(substr($value, 2));
  691. } elseif (\is_string($value) && 0 === strpos($value, '@')) {
  692. if (0 === strpos($value, '@@')) {
  693. $value = substr($value, 1);
  694. $invalidBehavior = null;
  695. } elseif (0 === strpos($value, '@!')) {
  696. $value = substr($value, 2);
  697. $invalidBehavior = ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
  698. } elseif (0 === strpos($value, '@?')) {
  699. $value = substr($value, 2);
  700. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  701. } else {
  702. $value = substr($value, 1);
  703. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  704. }
  705. if (null !== $invalidBehavior) {
  706. $value = new Reference($value, $invalidBehavior);
  707. }
  708. }
  709. return $value;
  710. }
  711. /**
  712. * Loads from Extensions.
  713. */
  714. private function loadFromExtensions(array $content)
  715. {
  716. foreach ($content as $namespace => $values) {
  717. if (\in_array($namespace, ['imports', 'parameters', 'services'])) {
  718. continue;
  719. }
  720. if (!\is_array($values) && null !== $values) {
  721. $values = [];
  722. }
  723. $this->container->loadFromExtension($namespace, $values);
  724. }
  725. }
  726. /**
  727. * Checks the keywords used to define a service.
  728. */
  729. private function checkDefinition(string $id, array $definition, string $file)
  730. {
  731. if ($this->isLoadingInstanceof) {
  732. $keywords = self::INSTANCEOF_KEYWORDS;
  733. } elseif (isset($definition['resource']) || isset($definition['namespace'])) {
  734. $keywords = self::PROTOTYPE_KEYWORDS;
  735. } else {
  736. $keywords = self::SERVICE_KEYWORDS;
  737. }
  738. foreach ($definition as $key => $value) {
  739. if (!isset($keywords[$key])) {
  740. throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported for definition "%s" in "%s". Allowed configuration keys are "%s".', $key, $id, $file, implode('", "', $keywords)));
  741. }
  742. }
  743. }
  744. }