YamlFileLoader.php 37 KB

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