YamlFileLoader.php 30 KB

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