YamlFileLoader.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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\AbstractArgument;
  13. use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
  14. use Symfony\Component\DependencyInjection\Argument\BoundArgument;
  15. use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
  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, string $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, string $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".', get_debug_type($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".', get_debug_type($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 (1 === \count($tag) && \is_array(current($tag))) {
  233. $name = key($tag);
  234. $tag = current($tag);
  235. } else {
  236. if (!isset($tag['name'])) {
  237. throw new InvalidArgumentException(sprintf('A "tags" entry in "_defaults" is missing a "name" key in "%s".', $file));
  238. }
  239. $name = $tag['name'];
  240. unset($tag['name']);
  241. }
  242. if (!\is_string($name) || '' === $name) {
  243. throw new InvalidArgumentException(sprintf('The tag name in "_defaults" must be a non-empty string in "%s".', $file));
  244. }
  245. foreach ($tag as $attribute => $value) {
  246. if (!is_scalar($value) && null !== $value) {
  247. 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));
  248. }
  249. }
  250. }
  251. }
  252. if (isset($defaults['bind'])) {
  253. if (!\is_array($defaults['bind'])) {
  254. throw new InvalidArgumentException(sprintf('Parameter "bind" in "_defaults" must be an array in "%s". Check your YAML syntax.', $file));
  255. }
  256. foreach ($this->resolveServices($defaults['bind'], $file) as $argument => $value) {
  257. $defaults['bind'][$argument] = new BoundArgument($value, true, BoundArgument::DEFAULTS_BINDING, $file);
  258. }
  259. }
  260. return $defaults;
  261. }
  262. private function isUsingShortSyntax(array $service): bool
  263. {
  264. foreach ($service as $key => $value) {
  265. if (\is_string($key) && ('' === $key || ('$' !== $key[0] && false === strpos($key, '\\')))) {
  266. return false;
  267. }
  268. }
  269. return true;
  270. }
  271. /**
  272. * Parses a definition.
  273. *
  274. * @param array|string|null $service
  275. *
  276. * @throws InvalidArgumentException When tags are invalid
  277. */
  278. private function parseDefinition(string $id, $service, string $file, array $defaults, bool $return = false)
  279. {
  280. if (preg_match('/^_[a-zA-Z0-9_]*$/', $id)) {
  281. throw new InvalidArgumentException(sprintf('Service names that start with an underscore are reserved. Rename the "%s" service or define it in XML instead.', $id));
  282. }
  283. if (\is_string($service) && 0 === strpos($service, '@')) {
  284. $alias = new Alias(substr($service, 1));
  285. if (isset($defaults['public'])) {
  286. $alias->setPublic($defaults['public']);
  287. }
  288. return $return ? $alias : $this->container->setAlias($id, $alias);
  289. }
  290. if (\is_array($service) && $this->isUsingShortSyntax($service)) {
  291. $service = ['arguments' => $service];
  292. }
  293. if (null === $service) {
  294. $service = [];
  295. }
  296. if (!\is_array($service)) {
  297. 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.', get_debug_type($service), $id, $file));
  298. }
  299. if (isset($service['stack'])) {
  300. if (!\is_array($service['stack'])) {
  301. throw new InvalidArgumentException(sprintf('A stack must be an array of definitions, "%s" given for service "%s" in "%s". Check your YAML syntax.', get_debug_type($service), $id, $file));
  302. }
  303. $stack = [];
  304. foreach ($service['stack'] as $k => $frame) {
  305. if (\is_array($frame) && 1 === \count($frame) && !isset(self::SERVICE_KEYWORDS[key($frame)])) {
  306. $frame = [
  307. 'class' => key($frame),
  308. 'arguments' => current($frame),
  309. ];
  310. }
  311. if (\is_array($frame) && isset($frame['stack'])) {
  312. throw new InvalidArgumentException(sprintf('Service stack "%s" cannot contain another stack in "%s".', $id, $file));
  313. }
  314. $definition = $this->parseDefinition($id.'" at index "'.$k, $frame, $file, $defaults, true);
  315. if ($definition instanceof Definition) {
  316. $definition->setInstanceofConditionals($this->instanceof);
  317. }
  318. $stack[$k] = $definition;
  319. }
  320. if ($diff = array_diff(array_keys($service), ['stack', 'public', 'deprecated'])) {
  321. throw new InvalidArgumentException(sprintf('Invalid attribute "%s"; supported ones are "public" and "deprecated" for service "%s" in "%s". Check your YAML syntax.', implode('", "', $diff), $id, $file));
  322. }
  323. $service = [
  324. 'parent' => '',
  325. 'arguments' => $stack,
  326. 'tags' => ['container.stack'],
  327. 'public' => $service['public'] ?? null,
  328. 'deprecated' => $service['deprecated'] ?? null,
  329. ];
  330. }
  331. $this->checkDefinition($id, $service, $file);
  332. if (isset($service['alias'])) {
  333. $alias = new Alias($service['alias']);
  334. if (isset($service['public'])) {
  335. $alias->setPublic($service['public']);
  336. } elseif (isset($defaults['public'])) {
  337. $alias->setPublic($defaults['public']);
  338. }
  339. foreach ($service as $key => $value) {
  340. if (!\in_array($key, ['alias', 'public', 'deprecated'])) {
  341. 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));
  342. }
  343. if ('deprecated' === $key) {
  344. $deprecation = \is_array($value) ? $value : ['message' => $value];
  345. if (!isset($deprecation['package'])) {
  346. trigger_deprecation('symfony/dependency-injection', '5.1', 'Not setting the attribute "package" of the "deprecated" option in "%s" is deprecated.', $file);
  347. }
  348. if (!isset($deprecation['version'])) {
  349. trigger_deprecation('symfony/dependency-injection', '5.1', 'Not setting the attribute "version" of the "deprecated" option in "%s" is deprecated.', $file);
  350. }
  351. $alias->setDeprecated($deprecation['package'] ?? '', $deprecation['version'] ?? '', $deprecation['message'] ?? '');
  352. }
  353. }
  354. return $return ? $alias : $this->container->setAlias($id, $alias);
  355. }
  356. if ($this->isLoadingInstanceof) {
  357. $definition = new ChildDefinition('');
  358. } elseif (isset($service['parent'])) {
  359. if ('' !== $service['parent'] && '@' === $service['parent'][0]) {
  360. 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)));
  361. }
  362. $definition = new ChildDefinition($service['parent']);
  363. } else {
  364. $definition = new Definition();
  365. }
  366. if (isset($defaults['public'])) {
  367. $definition->setPublic($defaults['public']);
  368. }
  369. if (isset($defaults['autowire'])) {
  370. $definition->setAutowired($defaults['autowire']);
  371. }
  372. if (isset($defaults['autoconfigure'])) {
  373. $definition->setAutoconfigured($defaults['autoconfigure']);
  374. }
  375. $definition->setChanges([]);
  376. if (isset($service['class'])) {
  377. $definition->setClass($service['class']);
  378. }
  379. if (isset($service['shared'])) {
  380. $definition->setShared($service['shared']);
  381. }
  382. if (isset($service['synthetic'])) {
  383. $definition->setSynthetic($service['synthetic']);
  384. }
  385. if (isset($service['lazy'])) {
  386. $definition->setLazy((bool) $service['lazy']);
  387. if (\is_string($service['lazy'])) {
  388. $definition->addTag('proxy', ['interface' => $service['lazy']]);
  389. }
  390. }
  391. if (isset($service['public'])) {
  392. $definition->setPublic($service['public']);
  393. }
  394. if (isset($service['abstract'])) {
  395. $definition->setAbstract($service['abstract']);
  396. }
  397. if (isset($service['deprecated'])) {
  398. $deprecation = \is_array($service['deprecated']) ? $service['deprecated'] : ['message' => $service['deprecated']];
  399. if (!isset($deprecation['package'])) {
  400. trigger_deprecation('symfony/dependency-injection', '5.1', 'Not setting the attribute "package" of the "deprecated" option in "%s" is deprecated.', $file);
  401. }
  402. if (!isset($deprecation['version'])) {
  403. trigger_deprecation('symfony/dependency-injection', '5.1', 'Not setting the attribute "version" of the "deprecated" option in "%s" is deprecated.', $file);
  404. }
  405. $definition->setDeprecated($deprecation['package'] ?? '', $deprecation['version'] ?? '', $deprecation['message'] ?? '');
  406. }
  407. if (isset($service['factory'])) {
  408. $definition->setFactory($this->parseCallable($service['factory'], 'factory', $id, $file));
  409. }
  410. if (isset($service['file'])) {
  411. $definition->setFile($service['file']);
  412. }
  413. if (isset($service['arguments'])) {
  414. $definition->setArguments($this->resolveServices($service['arguments'], $file));
  415. }
  416. if (isset($service['properties'])) {
  417. $definition->setProperties($this->resolveServices($service['properties'], $file));
  418. }
  419. if (isset($service['configurator'])) {
  420. $definition->setConfigurator($this->parseCallable($service['configurator'], 'configurator', $id, $file));
  421. }
  422. if (isset($service['calls'])) {
  423. if (!\is_array($service['calls'])) {
  424. throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  425. }
  426. foreach ($service['calls'] as $k => $call) {
  427. if (!\is_array($call) && (!\is_string($k) || !$call instanceof TaggedValue)) {
  428. throw new InvalidArgumentException(sprintf('Invalid method call for service "%s": expected map or array, "%s" given in "%s".', $id, $call instanceof TaggedValue ? '!'.$call->getTag() : get_debug_type($call), $file));
  429. }
  430. if (\is_string($k)) {
  431. throw new InvalidArgumentException(sprintf('Invalid method call for service "%s", did you forgot a leading dash before "%s: ..." in "%s"?', $id, $k, $file));
  432. }
  433. if (isset($call['method']) && \is_string($call['method'])) {
  434. $method = $call['method'];
  435. $args = $call['arguments'] ?? [];
  436. $returnsClone = $call['returns_clone'] ?? false;
  437. } else {
  438. if (1 === \count($call) && \is_string(key($call))) {
  439. $method = key($call);
  440. $args = $call[$method];
  441. if ($args instanceof TaggedValue) {
  442. if ('returns_clone' !== $args->getTag()) {
  443. throw new InvalidArgumentException(sprintf('Unsupported tag "!%s", did you mean "!returns_clone" for service "%s" in "%s"?', $args->getTag(), $id, $file));
  444. }
  445. $returnsClone = true;
  446. $args = $args->getValue();
  447. } else {
  448. $returnsClone = false;
  449. }
  450. } elseif (empty($call[0])) {
  451. 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));
  452. } else {
  453. $method = $call[0];
  454. $args = $call[1] ?? [];
  455. $returnsClone = $call[2] ?? false;
  456. }
  457. }
  458. if (!\is_array($args)) {
  459. 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));
  460. }
  461. $args = $this->resolveServices($args, $file);
  462. $definition->addMethodCall($method, $args, $returnsClone);
  463. }
  464. }
  465. $tags = $service['tags'] ?? [];
  466. if (!\is_array($tags)) {
  467. throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  468. }
  469. if (isset($defaults['tags'])) {
  470. $tags = array_merge($tags, $defaults['tags']);
  471. }
  472. foreach ($tags as $tag) {
  473. if (!\is_array($tag)) {
  474. $tag = ['name' => $tag];
  475. }
  476. if (1 === \count($tag) && \is_array(current($tag))) {
  477. $name = key($tag);
  478. $tag = current($tag);
  479. } else {
  480. if (!isset($tag['name'])) {
  481. throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in "%s".', $id, $file));
  482. }
  483. $name = $tag['name'];
  484. unset($tag['name']);
  485. }
  486. if (!\is_string($name) || '' === $name) {
  487. throw new InvalidArgumentException(sprintf('The tag name for service "%s" in "%s" must be a non-empty string.', $id, $file));
  488. }
  489. foreach ($tag as $attribute => $value) {
  490. if (!is_scalar($value) && null !== $value) {
  491. 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));
  492. }
  493. }
  494. $definition->addTag($name, $tag);
  495. }
  496. if (null !== $decorates = $service['decorates'] ?? null) {
  497. if ('' !== $decorates && '@' === $decorates[0]) {
  498. 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)));
  499. }
  500. $decorationOnInvalid = \array_key_exists('decoration_on_invalid', $service) ? $service['decoration_on_invalid'] : 'exception';
  501. if ('exception' === $decorationOnInvalid) {
  502. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  503. } elseif ('ignore' === $decorationOnInvalid) {
  504. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  505. } elseif (null === $decorationOnInvalid) {
  506. $invalidBehavior = ContainerInterface::NULL_ON_INVALID_REFERENCE;
  507. } elseif ('null' === $decorationOnInvalid) {
  508. 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));
  509. } else {
  510. 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));
  511. }
  512. $renameId = $service['decoration_inner_name'] ?? null;
  513. $priority = $service['decoration_priority'] ?? 0;
  514. $definition->setDecoratedService($decorates, $renameId, $priority, $invalidBehavior);
  515. }
  516. if (isset($service['autowire'])) {
  517. $definition->setAutowired($service['autowire']);
  518. }
  519. if (isset($defaults['bind']) || isset($service['bind'])) {
  520. // deep clone, to avoid multiple process of the same instance in the passes
  521. $bindings = isset($defaults['bind']) ? unserialize(serialize($defaults['bind'])) : [];
  522. if (isset($service['bind'])) {
  523. if (!\is_array($service['bind'])) {
  524. throw new InvalidArgumentException(sprintf('Parameter "bind" must be an array for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  525. }
  526. $bindings = array_merge($bindings, $this->resolveServices($service['bind'], $file));
  527. $bindingType = $this->isLoadingInstanceof ? BoundArgument::INSTANCEOF_BINDING : BoundArgument::SERVICE_BINDING;
  528. foreach ($bindings as $argument => $value) {
  529. if (!$value instanceof BoundArgument) {
  530. $bindings[$argument] = new BoundArgument($value, true, $bindingType, $file);
  531. }
  532. }
  533. }
  534. $definition->setBindings($bindings);
  535. }
  536. if (isset($service['autoconfigure'])) {
  537. $definition->setAutoconfigured($service['autoconfigure']);
  538. }
  539. if (\array_key_exists('namespace', $service) && !\array_key_exists('resource', $service)) {
  540. 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));
  541. }
  542. if ($return) {
  543. if (\array_key_exists('resource', $service)) {
  544. throw new InvalidArgumentException(sprintf('Invalid "resource" attribute found for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  545. }
  546. return $definition;
  547. }
  548. if (\array_key_exists('resource', $service)) {
  549. if (!\is_string($service['resource'])) {
  550. throw new InvalidArgumentException(sprintf('A "resource" attribute must be of type string for service "%s" in "%s". Check your YAML syntax.', $id, $file));
  551. }
  552. $exclude = $service['exclude'] ?? null;
  553. $namespace = $service['namespace'] ?? $id;
  554. $this->registerClasses($definition, $namespace, $service['resource'], $exclude);
  555. } else {
  556. $this->setDefinition($id, $definition);
  557. }
  558. }
  559. /**
  560. * Parses a callable.
  561. *
  562. * @param string|array $callable A callable reference
  563. *
  564. * @throws InvalidArgumentException When errors occur
  565. *
  566. * @return string|array|Reference A parsed callable
  567. */
  568. private function parseCallable($callable, string $parameter, string $id, string $file)
  569. {
  570. if (\is_string($callable)) {
  571. if ('' !== $callable && '@' === $callable[0]) {
  572. if (false === strpos($callable, ':')) {
  573. return [$this->resolveServices($callable, $file), '__invoke'];
  574. }
  575. 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));
  576. }
  577. return $callable;
  578. }
  579. if (\is_array($callable)) {
  580. if (isset($callable[0]) && isset($callable[1])) {
  581. return [$this->resolveServices($callable[0], $file), $callable[1]];
  582. }
  583. if ('factory' === $parameter && isset($callable[1]) && null === $callable[0]) {
  584. return $callable;
  585. }
  586. 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));
  587. }
  588. 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));
  589. }
  590. /**
  591. * Loads a YAML file.
  592. *
  593. * @param string $file
  594. *
  595. * @return array The file content
  596. *
  597. * @throws InvalidArgumentException when the given file is not a local file or when it does not exist
  598. */
  599. protected function loadFile($file)
  600. {
  601. if (!class_exists(\Symfony\Component\Yaml\Parser::class)) {
  602. throw new RuntimeException('Unable to load YAML config files as the Symfony Yaml Component is not installed.');
  603. }
  604. if (!stream_is_local($file)) {
  605. throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
  606. }
  607. if (!is_file($file)) {
  608. throw new InvalidArgumentException(sprintf('The file "%s" does not exist.', $file));
  609. }
  610. if (null === $this->yamlParser) {
  611. $this->yamlParser = new YamlParser();
  612. }
  613. try {
  614. $configuration = $this->yamlParser->parseFile($file, Yaml::PARSE_CONSTANT | Yaml::PARSE_CUSTOM_TAGS);
  615. } catch (ParseException $e) {
  616. throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML: ', $file).$e->getMessage(), 0, $e);
  617. }
  618. return $this->validate($configuration, $file);
  619. }
  620. /**
  621. * Validates a YAML file.
  622. *
  623. * @throws InvalidArgumentException When service file is not valid
  624. */
  625. private function validate($content, string $file): ?array
  626. {
  627. if (null === $content) {
  628. return $content;
  629. }
  630. if (!\is_array($content)) {
  631. throw new InvalidArgumentException(sprintf('The service file "%s" is not valid. It should contain an array. Check your YAML syntax.', $file));
  632. }
  633. foreach ($content as $namespace => $data) {
  634. if (\in_array($namespace, ['imports', 'parameters', 'services'])) {
  635. continue;
  636. }
  637. if (!$this->container->hasExtension($namespace)) {
  638. $extensionNamespaces = array_filter(array_map(function (ExtensionInterface $ext) { return $ext->getAlias(); }, $this->container->getExtensions()));
  639. 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'));
  640. }
  641. }
  642. return $content;
  643. }
  644. /**
  645. * Resolves services.
  646. *
  647. * @return array|string|Reference|ArgumentInterface
  648. */
  649. private function resolveServices($value, string $file, bool $isParameter = false)
  650. {
  651. if ($value instanceof TaggedValue) {
  652. $argument = $value->getValue();
  653. if ('iterator' === $value->getTag()) {
  654. if (!\is_array($argument)) {
  655. throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts sequences in "%s".', $file));
  656. }
  657. $argument = $this->resolveServices($argument, $file, $isParameter);
  658. try {
  659. return new IteratorArgument($argument);
  660. } catch (InvalidArgumentException $e) {
  661. throw new InvalidArgumentException(sprintf('"!iterator" tag only accepts arrays of "@service" references in "%s".', $file));
  662. }
  663. }
  664. if ('service_locator' === $value->getTag()) {
  665. if (!\is_array($argument)) {
  666. throw new InvalidArgumentException(sprintf('"!service_locator" tag only accepts maps in "%s".', $file));
  667. }
  668. $argument = $this->resolveServices($argument, $file, $isParameter);
  669. try {
  670. return new ServiceLocatorArgument($argument);
  671. } catch (InvalidArgumentException $e) {
  672. throw new InvalidArgumentException(sprintf('"!service_locator" tag only accepts maps of "@service" references in "%s".', $file));
  673. }
  674. }
  675. if (\in_array($value->getTag(), ['tagged', 'tagged_iterator', 'tagged_locator'], true)) {
  676. $forLocator = 'tagged_locator' === $value->getTag();
  677. if (\is_array($argument) && isset($argument['tag']) && $argument['tag']) {
  678. if ($diff = array_diff(array_keys($argument), ['tag', 'index_by', 'default_index_method', 'default_priority_method'])) {
  679. 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)));
  680. }
  681. $argument = new TaggedIteratorArgument($argument['tag'], $argument['index_by'] ?? null, $argument['default_index_method'] ?? null, $forLocator, $argument['default_priority_method'] ?? null);
  682. } elseif (\is_string($argument) && $argument) {
  683. $argument = new TaggedIteratorArgument($argument, null, null, $forLocator);
  684. } else {
  685. throw new InvalidArgumentException(sprintf('"!%s" tags only accept a non empty string or an array with a key "tag" in "%s".', $value->getTag(), $file));
  686. }
  687. if ($forLocator) {
  688. $argument = new ServiceLocatorArgument($argument);
  689. }
  690. return $argument;
  691. }
  692. if ('service' === $value->getTag()) {
  693. if ($isParameter) {
  694. throw new InvalidArgumentException(sprintf('Using an anonymous service in a parameter is not allowed in "%s".', $file));
  695. }
  696. $isLoadingInstanceof = $this->isLoadingInstanceof;
  697. $this->isLoadingInstanceof = false;
  698. $instanceof = $this->instanceof;
  699. $this->instanceof = [];
  700. $id = sprintf('.%d_%s', ++$this->anonymousServicesCount, preg_replace('/^.*\\\\/', '', $argument['class'] ?? '').$this->anonymousServicesSuffix);
  701. $this->parseDefinition($id, $argument, $file, []);
  702. if (!$this->container->hasDefinition($id)) {
  703. throw new InvalidArgumentException(sprintf('Creating an alias using the tag "!service" is not allowed in "%s".', $file));
  704. }
  705. $this->container->getDefinition($id);
  706. $this->isLoadingInstanceof = $isLoadingInstanceof;
  707. $this->instanceof = $instanceof;
  708. return new Reference($id);
  709. }
  710. if ('abstract' === $value->getTag()) {
  711. return new AbstractArgument($value->getValue());
  712. }
  713. throw new InvalidArgumentException(sprintf('Unsupported tag "!%s".', $value->getTag()));
  714. }
  715. if (\is_array($value)) {
  716. foreach ($value as $k => $v) {
  717. $value[$k] = $this->resolveServices($v, $file, $isParameter);
  718. }
  719. } elseif (\is_string($value) && 0 === strpos($value, '@=')) {
  720. if (!class_exists(Expression::class)) {
  721. throw new \LogicException('The "@=" expression syntax cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
  722. }
  723. return new Expression(substr($value, 2));
  724. } elseif (\is_string($value) && 0 === strpos($value, '@')) {
  725. if (0 === strpos($value, '@@')) {
  726. $value = substr($value, 1);
  727. $invalidBehavior = null;
  728. } elseif (0 === strpos($value, '@!')) {
  729. $value = substr($value, 2);
  730. $invalidBehavior = ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
  731. } elseif (0 === strpos($value, '@?')) {
  732. $value = substr($value, 2);
  733. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  734. } else {
  735. $value = substr($value, 1);
  736. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  737. }
  738. if (null !== $invalidBehavior) {
  739. $value = new Reference($value, $invalidBehavior);
  740. }
  741. }
  742. return $value;
  743. }
  744. /**
  745. * Loads from Extensions.
  746. */
  747. private function loadFromExtensions(array $content)
  748. {
  749. foreach ($content as $namespace => $values) {
  750. if (\in_array($namespace, ['imports', 'parameters', 'services'])) {
  751. continue;
  752. }
  753. if (!\is_array($values) && null !== $values) {
  754. $values = [];
  755. }
  756. $this->container->loadFromExtension($namespace, $values);
  757. }
  758. }
  759. /**
  760. * Checks the keywords used to define a service.
  761. */
  762. private function checkDefinition(string $id, array $definition, string $file)
  763. {
  764. if ($this->isLoadingInstanceof) {
  765. $keywords = self::INSTANCEOF_KEYWORDS;
  766. } elseif (isset($definition['resource']) || isset($definition['namespace'])) {
  767. $keywords = self::PROTOTYPE_KEYWORDS;
  768. } else {
  769. $keywords = self::SERVICE_KEYWORDS;
  770. }
  771. foreach ($definition as $key => $value) {
  772. if (!isset($keywords[$key])) {
  773. 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)));
  774. }
  775. }
  776. }
  777. }