YamlFileLoader.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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\Config\Resource\FileResource;
  12. use Symfony\Component\DependencyInjection\Alias;
  13. use Symfony\Component\DependencyInjection\ContainerInterface;
  14. use Symfony\Component\DependencyInjection\Definition;
  15. use Symfony\Component\DependencyInjection\DefinitionDecorator;
  16. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  17. use Symfony\Component\DependencyInjection\Exception\RuntimeException;
  18. use Symfony\Component\DependencyInjection\Reference;
  19. use Symfony\Component\ExpressionLanguage\Expression;
  20. use Symfony\Component\Yaml\Exception\ParseException;
  21. use Symfony\Component\Yaml\Parser as YamlParser;
  22. /**
  23. * YamlFileLoader loads YAML files service definitions.
  24. *
  25. * The YAML format does not support anonymous services (cf. the XML loader).
  26. *
  27. * @author Fabien Potencier <fabien@symfony.com>
  28. */
  29. class YamlFileLoader extends FileLoader
  30. {
  31. private $yamlParser;
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function load($resource, $type = null)
  36. {
  37. $path = $this->locator->locate($resource);
  38. $content = $this->loadFile($path);
  39. $this->container->addResource(new FileResource($path));
  40. // empty file
  41. if (null === $content) {
  42. return;
  43. }
  44. // imports
  45. $this->parseImports($content, $path);
  46. // parameters
  47. if (isset($content['parameters'])) {
  48. if (!\is_array($content['parameters'])) {
  49. throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in %s. Check your YAML syntax.', $resource));
  50. }
  51. foreach ($content['parameters'] as $key => $value) {
  52. $this->container->setParameter($key, $this->resolveServices($value));
  53. }
  54. }
  55. // extensions
  56. $this->loadFromExtensions($content);
  57. // services
  58. $this->parseDefinitions($content, $resource);
  59. }
  60. /**
  61. * {@inheritdoc}
  62. */
  63. public function supports($resource, $type = null)
  64. {
  65. return \is_string($resource) && \in_array(pathinfo($resource, PATHINFO_EXTENSION), array('yml', 'yaml'), true);
  66. }
  67. /**
  68. * Parses all imports.
  69. *
  70. * @param array $content
  71. * @param string $file
  72. */
  73. private function parseImports(array $content, $file)
  74. {
  75. if (!isset($content['imports'])) {
  76. return;
  77. }
  78. if (!\is_array($content['imports'])) {
  79. throw new InvalidArgumentException(sprintf('The "imports" key should contain an array in %s. Check your YAML syntax.', $file));
  80. }
  81. $defaultDirectory = \dirname($file);
  82. foreach ($content['imports'] as $import) {
  83. if (!\is_array($import)) {
  84. throw new InvalidArgumentException(sprintf('The values in the "imports" key should be arrays in %s. Check your YAML syntax.', $file));
  85. }
  86. $this->setCurrentDir($defaultDirectory);
  87. $this->import($import['resource'], null, isset($import['ignore_errors']) ? (bool) $import['ignore_errors'] : false, $file);
  88. }
  89. }
  90. /**
  91. * Parses definitions.
  92. *
  93. * @param array $content
  94. * @param string $file
  95. */
  96. private function parseDefinitions(array $content, $file)
  97. {
  98. if (!isset($content['services'])) {
  99. return;
  100. }
  101. if (!\is_array($content['services'])) {
  102. throw new InvalidArgumentException(sprintf('The "services" key should contain an array in %s. Check your YAML syntax.', $file));
  103. }
  104. foreach ($content['services'] as $id => $service) {
  105. $this->parseDefinition($id, $service, $file);
  106. }
  107. }
  108. /**
  109. * Parses a definition.
  110. *
  111. * @param string $id
  112. * @param array|string $service
  113. * @param string $file
  114. *
  115. * @throws InvalidArgumentException When tags are invalid
  116. */
  117. private function parseDefinition($id, $service, $file)
  118. {
  119. if (\is_string($service) && 0 === strpos($service, '@')) {
  120. $this->container->setAlias($id, substr($service, 1));
  121. return;
  122. }
  123. if (!\is_array($service)) {
  124. 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));
  125. }
  126. if (isset($service['alias'])) {
  127. $public = !array_key_exists('public', $service) || (bool) $service['public'];
  128. $this->container->setAlias($id, new Alias($service['alias'], $public));
  129. return;
  130. }
  131. if (isset($service['parent'])) {
  132. $definition = new DefinitionDecorator($service['parent']);
  133. } else {
  134. $definition = new Definition();
  135. }
  136. if (isset($service['class'])) {
  137. $definition->setClass($service['class']);
  138. }
  139. if (isset($service['shared'])) {
  140. $definition->setShared($service['shared']);
  141. }
  142. if (isset($service['scope'])) {
  143. if ('request' !== $id) {
  144. @trigger_error(sprintf('The "scope" key of service "%s" in file "%s" is deprecated since Symfony 2.8 and will be removed in 3.0.', $id, $file), E_USER_DEPRECATED);
  145. }
  146. $definition->setScope($service['scope'], false);
  147. }
  148. if (isset($service['synthetic'])) {
  149. $definition->setSynthetic($service['synthetic']);
  150. }
  151. if (isset($service['synchronized'])) {
  152. @trigger_error(sprintf('The "synchronized" key of service "%s" in file "%s" is deprecated since Symfony 2.7 and will be removed in 3.0.', $id, $file), E_USER_DEPRECATED);
  153. $definition->setSynchronized($service['synchronized'], 'request' !== $id);
  154. }
  155. if (isset($service['lazy'])) {
  156. $definition->setLazy($service['lazy']);
  157. }
  158. if (isset($service['public'])) {
  159. $definition->setPublic($service['public']);
  160. }
  161. if (isset($service['abstract'])) {
  162. $definition->setAbstract($service['abstract']);
  163. }
  164. if (array_key_exists('deprecated', $service)) {
  165. $definition->setDeprecated(true, $service['deprecated']);
  166. }
  167. if (isset($service['factory'])) {
  168. if (\is_string($service['factory'])) {
  169. if (false !== strpos($service['factory'], ':') && false === strpos($service['factory'], '::')) {
  170. $parts = explode(':', $service['factory']);
  171. $definition->setFactory(array($this->resolveServices('@'.$parts[0]), $parts[1]));
  172. } else {
  173. $definition->setFactory($service['factory']);
  174. }
  175. } else {
  176. $definition->setFactory(array($this->resolveServices($service['factory'][0]), $service['factory'][1]));
  177. }
  178. }
  179. if (isset($service['factory_class'])) {
  180. @trigger_error(sprintf('The "factory_class" key of service "%s" in file "%s" is deprecated since Symfony 2.6 and will be removed in 3.0. Use "factory" instead.', $id, $file), E_USER_DEPRECATED);
  181. $definition->setFactoryClass($service['factory_class']);
  182. }
  183. if (isset($service['factory_method'])) {
  184. @trigger_error(sprintf('The "factory_method" key of service "%s" in file "%s" is deprecated since Symfony 2.6 and will be removed in 3.0. Use "factory" instead.', $id, $file), E_USER_DEPRECATED);
  185. $definition->setFactoryMethod($service['factory_method']);
  186. }
  187. if (isset($service['factory_service'])) {
  188. @trigger_error(sprintf('The "factory_service" key of service "%s" in file "%s" is deprecated since Symfony 2.6 and will be removed in 3.0. Use "factory" instead.', $id, $file), E_USER_DEPRECATED);
  189. $definition->setFactoryService($service['factory_service']);
  190. }
  191. if (isset($service['file'])) {
  192. $definition->setFile($service['file']);
  193. }
  194. if (isset($service['arguments'])) {
  195. $definition->setArguments($this->resolveServices($service['arguments']));
  196. }
  197. if (isset($service['properties'])) {
  198. $definition->setProperties($this->resolveServices($service['properties']));
  199. }
  200. if (isset($service['configurator'])) {
  201. if (\is_string($service['configurator'])) {
  202. $definition->setConfigurator($service['configurator']);
  203. } else {
  204. $definition->setConfigurator(array($this->resolveServices($service['configurator'][0]), $service['configurator'][1]));
  205. }
  206. }
  207. if (isset($service['calls'])) {
  208. if (!\is_array($service['calls'])) {
  209. throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
  210. }
  211. foreach ($service['calls'] as $call) {
  212. if (isset($call['method'])) {
  213. $method = $call['method'];
  214. $args = isset($call['arguments']) ? $this->resolveServices($call['arguments']) : array();
  215. } else {
  216. $method = $call[0];
  217. $args = isset($call[1]) ? $this->resolveServices($call[1]) : array();
  218. }
  219. $definition->addMethodCall($method, $args);
  220. }
  221. }
  222. if (isset($service['tags'])) {
  223. if (!\is_array($service['tags'])) {
  224. throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
  225. }
  226. foreach ($service['tags'] as $tag) {
  227. if (!\is_array($tag)) {
  228. throw new InvalidArgumentException(sprintf('A "tags" entry must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
  229. }
  230. if (!isset($tag['name'])) {
  231. throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file));
  232. }
  233. if (!\is_string($tag['name']) || '' === $tag['name']) {
  234. throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', $id, $file));
  235. }
  236. $name = $tag['name'];
  237. unset($tag['name']);
  238. foreach ($tag as $attribute => $value) {
  239. if (!is_scalar($value) && null !== $value) {
  240. 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));
  241. }
  242. }
  243. $definition->addTag($name, $tag);
  244. }
  245. }
  246. if (isset($service['decorates'])) {
  247. if ('' !== $service['decorates'] && '@' === $service['decorates'][0]) {
  248. 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)));
  249. }
  250. $renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null;
  251. $priority = isset($service['decoration_priority']) ? $service['decoration_priority'] : 0;
  252. $definition->setDecoratedService($service['decorates'], $renameId, $priority);
  253. }
  254. if (isset($service['autowire'])) {
  255. $definition->setAutowired($service['autowire']);
  256. }
  257. if (isset($service['autowiring_types'])) {
  258. if (\is_string($service['autowiring_types'])) {
  259. $definition->addAutowiringType($service['autowiring_types']);
  260. } else {
  261. if (!\is_array($service['autowiring_types'])) {
  262. 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));
  263. }
  264. foreach ($service['autowiring_types'] as $autowiringType) {
  265. if (!\is_string($autowiringType)) {
  266. throw new InvalidArgumentException(sprintf('A "autowiring_types" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file));
  267. }
  268. $definition->addAutowiringType($autowiringType);
  269. }
  270. }
  271. }
  272. $this->container->setDefinition($id, $definition);
  273. }
  274. /**
  275. * Loads a YAML file.
  276. *
  277. * @param string $file
  278. *
  279. * @return array The file content
  280. *
  281. * @throws InvalidArgumentException when the given file is not a local file or when it does not exist
  282. */
  283. protected function loadFile($file)
  284. {
  285. if (!class_exists('Symfony\Component\Yaml\Parser')) {
  286. throw new RuntimeException('Unable to load YAML config files as the Symfony Yaml Component is not installed.');
  287. }
  288. if (!stream_is_local($file)) {
  289. throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
  290. }
  291. if (!file_exists($file)) {
  292. throw new InvalidArgumentException(sprintf('The file "%s" does not exist.', $file));
  293. }
  294. if (null === $this->yamlParser) {
  295. $this->yamlParser = new YamlParser();
  296. }
  297. try {
  298. $configuration = $this->yamlParser->parse(file_get_contents($file));
  299. } catch (ParseException $e) {
  300. throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $file), 0, $e);
  301. }
  302. return $this->validate($configuration, $file);
  303. }
  304. /**
  305. * Validates a YAML file.
  306. *
  307. * @param mixed $content
  308. * @param string $file
  309. *
  310. * @return array
  311. *
  312. * @throws InvalidArgumentException When service file is not valid
  313. */
  314. private function validate($content, $file)
  315. {
  316. if (null === $content) {
  317. return $content;
  318. }
  319. if (!\is_array($content)) {
  320. throw new InvalidArgumentException(sprintf('The service file "%s" is not valid. It should contain an array. Check your YAML syntax.', $file));
  321. }
  322. foreach ($content as $namespace => $data) {
  323. if (\in_array($namespace, array('imports', 'parameters', 'services'))) {
  324. continue;
  325. }
  326. if (!$this->container->hasExtension($namespace)) {
  327. $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getAlias(); }, $this->container->getExtensions()));
  328. 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'));
  329. }
  330. }
  331. return $content;
  332. }
  333. /**
  334. * Resolves services.
  335. *
  336. * @param string|array $value
  337. *
  338. * @return array|string|Reference
  339. */
  340. private function resolveServices($value)
  341. {
  342. if (\is_array($value)) {
  343. $value = array_map(array($this, 'resolveServices'), $value);
  344. } elseif (\is_string($value) && 0 === strpos($value, '@=')) {
  345. return new Expression(substr($value, 2));
  346. } elseif (\is_string($value) && 0 === strpos($value, '@')) {
  347. if (0 === strpos($value, '@@')) {
  348. $value = substr($value, 1);
  349. $invalidBehavior = null;
  350. } elseif (0 === strpos($value, '@?')) {
  351. $value = substr($value, 2);
  352. $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
  353. } else {
  354. $value = substr($value, 1);
  355. $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
  356. }
  357. if ('=' === substr($value, -1)) {
  358. $value = substr($value, 0, -1);
  359. $strict = false;
  360. } else {
  361. $strict = true;
  362. }
  363. if (null !== $invalidBehavior) {
  364. $value = new Reference($value, $invalidBehavior, $strict);
  365. }
  366. }
  367. return $value;
  368. }
  369. /**
  370. * Loads from Extensions.
  371. */
  372. private function loadFromExtensions(array $content)
  373. {
  374. foreach ($content as $namespace => $values) {
  375. if (\in_array($namespace, array('imports', 'parameters', 'services'))) {
  376. continue;
  377. }
  378. if (!\is_array($values) && null !== $values) {
  379. $values = array();
  380. }
  381. $this->container->loadFromExtension($namespace, $values);
  382. }
  383. }
  384. }