4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DependencyInjection\Loader;
14 use Symfony\Component\DependencyInjection\DefinitionDecorator;
15 use Symfony\Component\DependencyInjection\Alias;
16 use Symfony\Component\DependencyInjection\ContainerInterface;
17 use Symfony\Component\DependencyInjection\Definition;
18 use Symfony\Component\DependencyInjection\Reference;
19 use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
20 use Symfony\Component\DependencyInjection\Exception\RuntimeException;
21 use Symfony\Component\Config\Resource\FileResource;
22 use Symfony\Component\Yaml\Exception\ParseException;
23 use Symfony\Component\Yaml\Parser as YamlParser;
24 use Symfony\Component\Yaml\Yaml;
25 use Symfony\Component\ExpressionLanguage\Expression;
28 * YamlFileLoader loads YAML files service definitions.
30 * The YAML format does not support anonymous services (cf. the XML loader).
32 * @author Fabien Potencier <fabien@symfony.com>
34 class YamlFileLoader extends FileLoader
36 private static $keywords = array(
41 'synthetic' => 'synthetic',
44 'abstract' => 'abstract',
45 'deprecated' => 'deprecated',
46 'factory' => 'factory',
48 'arguments' => 'arguments',
49 'properties' => 'properties',
50 'configurator' => 'configurator',
53 'decorates' => 'decorates',
54 'decoration_inner_name' => 'decoration_inner_name',
55 'decoration_priority' => 'decoration_priority',
56 'autowire' => 'autowire',
57 'autowiring_types' => 'autowiring_types',
65 public function load($resource, $type = null)
67 $path = $this->locator->locate($resource);
69 $content = $this->loadFile($path);
71 $this->container->addResource(new FileResource($path));
74 if (null === $content) {
79 $this->parseImports($content, $path);
82 if (isset($content['parameters'])) {
83 if (!is_array($content['parameters'])) {
84 throw new InvalidArgumentException(sprintf('The "parameters" key should contain an array in %s. Check your YAML syntax.', $resource));
87 foreach ($content['parameters'] as $key => $value) {
88 $this->container->setParameter($key, $this->resolveServices($value));
93 $this->loadFromExtensions($content);
96 $this->parseDefinitions($content, $resource);
102 public function supports($resource, $type = null)
104 return is_string($resource) && in_array(pathinfo($resource, PATHINFO_EXTENSION), array('yml', 'yaml'), true);
108 * Parses all imports.
110 * @param array $content
111 * @param string $file
113 private function parseImports(array $content, $file)
115 if (!isset($content['imports'])) {
119 if (!is_array($content['imports'])) {
120 throw new InvalidArgumentException(sprintf('The "imports" key should contain an array in %s. Check your YAML syntax.', $file));
123 $defaultDirectory = dirname($file);
124 foreach ($content['imports'] as $import) {
125 if (!is_array($import)) {
126 throw new InvalidArgumentException(sprintf('The values in the "imports" key should be arrays in %s. Check your YAML syntax.', $file));
129 $this->setCurrentDir($defaultDirectory);
130 $this->import($import['resource'], null, isset($import['ignore_errors']) ? (bool) $import['ignore_errors'] : false, $file);
135 * Parses definitions.
137 * @param array $content
138 * @param string $file
140 private function parseDefinitions(array $content, $file)
142 if (!isset($content['services'])) {
146 if (!is_array($content['services'])) {
147 throw new InvalidArgumentException(sprintf('The "services" key should contain an array in %s. Check your YAML syntax.', $file));
150 foreach ($content['services'] as $id => $service) {
151 $this->parseDefinition($id, $service, $file);
156 * Parses a definition.
159 * @param array|string $service
160 * @param string $file
162 * @throws InvalidArgumentException When tags are invalid
164 private function parseDefinition($id, $service, $file)
166 if (is_string($service) && 0 === strpos($service, '@')) {
167 $this->container->setAlias($id, substr($service, 1));
172 if (!is_array($service)) {
173 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));
176 static::checkDefinition($id, $service, $file);
178 if (isset($service['alias'])) {
179 $public = !array_key_exists('public', $service) || (bool) $service['public'];
180 $this->container->setAlias($id, new Alias($service['alias'], $public));
182 foreach ($service as $key => $value) {
183 if (!in_array($key, array('alias', 'public'))) {
184 @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);
191 if (isset($service['parent'])) {
192 $definition = new DefinitionDecorator($service['parent']);
194 $definition = new Definition();
197 if (isset($service['class'])) {
198 $definition->setClass($service['class']);
201 if (isset($service['shared'])) {
202 $definition->setShared($service['shared']);
205 if (isset($service['synthetic'])) {
206 $definition->setSynthetic($service['synthetic']);
209 if (isset($service['lazy'])) {
210 $definition->setLazy($service['lazy']);
213 if (isset($service['public'])) {
214 $definition->setPublic($service['public']);
217 if (isset($service['abstract'])) {
218 $definition->setAbstract($service['abstract']);
221 if (array_key_exists('deprecated', $service)) {
222 $definition->setDeprecated(true, $service['deprecated']);
225 if (isset($service['factory'])) {
226 $definition->setFactory($this->parseCallable($service['factory'], 'factory', $id, $file));
229 if (isset($service['file'])) {
230 $definition->setFile($service['file']);
233 if (isset($service['arguments'])) {
234 $definition->setArguments($this->resolveServices($service['arguments']));
237 if (isset($service['properties'])) {
238 $definition->setProperties($this->resolveServices($service['properties']));
241 if (isset($service['configurator'])) {
242 $definition->setConfigurator($this->parseCallable($service['configurator'], 'configurator', $id, $file));
245 if (isset($service['calls'])) {
246 if (!is_array($service['calls'])) {
247 throw new InvalidArgumentException(sprintf('Parameter "calls" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
250 foreach ($service['calls'] as $call) {
251 if (isset($call['method'])) {
252 $method = $call['method'];
253 $args = isset($call['arguments']) ? $this->resolveServices($call['arguments']) : array();
256 $args = isset($call[1]) ? $this->resolveServices($call[1]) : array();
259 $definition->addMethodCall($method, $args);
263 if (isset($service['tags'])) {
264 if (!is_array($service['tags'])) {
265 throw new InvalidArgumentException(sprintf('Parameter "tags" must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
268 foreach ($service['tags'] as $tag) {
269 if (!is_array($tag)) {
270 throw new InvalidArgumentException(sprintf('A "tags" entry must be an array for service "%s" in %s. Check your YAML syntax.', $id, $file));
273 if (!isset($tag['name'])) {
274 throw new InvalidArgumentException(sprintf('A "tags" entry is missing a "name" key for service "%s" in %s.', $id, $file));
277 if (!is_string($tag['name']) || '' === $tag['name']) {
278 throw new InvalidArgumentException(sprintf('The tag name for service "%s" in %s must be a non-empty string.', $id, $file));
281 $name = $tag['name'];
284 foreach ($tag as $attribute => $value) {
285 if (!is_scalar($value) && null !== $value) {
286 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));
290 $definition->addTag($name, $tag);
294 if (isset($service['decorates'])) {
295 if ('' !== $service['decorates'] && '@' === $service['decorates'][0]) {
296 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)));
299 $renameId = isset($service['decoration_inner_name']) ? $service['decoration_inner_name'] : null;
300 $priority = isset($service['decoration_priority']) ? $service['decoration_priority'] : 0;
301 $definition->setDecoratedService($service['decorates'], $renameId, $priority);
304 if (isset($service['autowire'])) {
305 $definition->setAutowired($service['autowire']);
308 if (isset($service['autowiring_types'])) {
309 if (is_string($service['autowiring_types'])) {
310 $definition->addAutowiringType($service['autowiring_types']);
312 if (!is_array($service['autowiring_types'])) {
313 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));
316 foreach ($service['autowiring_types'] as $autowiringType) {
317 if (!is_string($autowiringType)) {
318 throw new InvalidArgumentException(sprintf('A "autowiring_types" attribute must be of type string for service "%s" in %s. Check your YAML syntax.', $id, $file));
321 $definition->addAutowiringType($autowiringType);
326 $this->container->setDefinition($id, $definition);
332 * @param string|array $callable A callable
333 * @param string $parameter A parameter (e.g. 'factory' or 'configurator')
334 * @param string $id A service identifier
335 * @param string $file A parsed file
337 * @throws InvalidArgumentException When errors are occuried
339 * @return string|array A parsed callable
341 private function parseCallable($callable, $parameter, $id, $file)
343 if (is_string($callable)) {
344 if ('' !== $callable && '@' === $callable[0]) {
345 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)));
348 if (false !== strpos($callable, ':') && false === strpos($callable, '::')) {
349 $parts = explode(':', $callable);
351 return array($this->resolveServices('@'.$parts[0]), $parts[1]);
357 if (is_array($callable)) {
358 if (isset($callable[0]) && isset($callable[1])) {
359 return array($this->resolveServices($callable[0]), $callable[1]);
362 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));
365 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));
371 * @param string $file
373 * @return array The file content
375 * @throws InvalidArgumentException when the given file is not a local file or when it does not exist
377 protected function loadFile($file)
379 if (!class_exists('Symfony\Component\Yaml\Parser')) {
380 throw new RuntimeException('Unable to load YAML config files as the Symfony Yaml Component is not installed.');
383 if (!stream_is_local($file)) {
384 throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file));
387 if (!file_exists($file)) {
388 throw new InvalidArgumentException(sprintf('The file "%s" does not exist.', $file));
391 if (null === $this->yamlParser) {
392 $this->yamlParser = new YamlParser();
396 $configuration = $this->yamlParser->parse(file_get_contents($file), Yaml::PARSE_CONSTANT);
397 } catch (ParseException $e) {
398 throw new InvalidArgumentException(sprintf('The file "%s" does not contain valid YAML.', $file), 0, $e);
401 return $this->validate($configuration, $file);
405 * Validates a YAML file.
407 * @param mixed $content
408 * @param string $file
412 * @throws InvalidArgumentException When service file is not valid
414 private function validate($content, $file)
416 if (null === $content) {
420 if (!is_array($content)) {
421 throw new InvalidArgumentException(sprintf('The service file "%s" is not valid. It should contain an array. Check your YAML syntax.', $file));
424 foreach ($content as $namespace => $data) {
425 if (in_array($namespace, array('imports', 'parameters', 'services'))) {
429 if (!$this->container->hasExtension($namespace)) {
430 $extensionNamespaces = array_filter(array_map(function ($ext) { return $ext->getAlias(); }, $this->container->getExtensions()));
431 throw new InvalidArgumentException(sprintf(
432 'There is no extension able to load the configuration for "%s" (in %s). Looked for namespace "%s", found %s',
436 $extensionNamespaces ? sprintf('"%s"', implode('", "', $extensionNamespaces)) : 'none'
447 * @param string|array $value
449 * @return array|string|Reference
451 private function resolveServices($value)
453 if (is_array($value)) {
454 $value = array_map(array($this, 'resolveServices'), $value);
455 } elseif (is_string($value) && 0 === strpos($value, '@=')) {
456 return new Expression(substr($value, 2));
457 } elseif (is_string($value) && 0 === strpos($value, '@')) {
458 if (0 === strpos($value, '@@')) {
459 $value = substr($value, 1);
460 $invalidBehavior = null;
461 } elseif (0 === strpos($value, '@?')) {
462 $value = substr($value, 2);
463 $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
465 $value = substr($value, 1);
466 $invalidBehavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE;
469 if ('=' === substr($value, -1)) {
470 $value = substr($value, 0, -1);
473 if (null !== $invalidBehavior) {
474 $value = new Reference($value, $invalidBehavior);
482 * Loads from Extensions.
484 * @param array $content
486 private function loadFromExtensions(array $content)
488 foreach ($content as $namespace => $values) {
489 if (in_array($namespace, array('imports', 'parameters', 'services'))) {
493 if (!is_array($values)) {
497 $this->container->loadFromExtension($namespace, $values);
502 * Checks the keywords used to define a service.
504 * @param string $id The service name
505 * @param array $definition The service definition to check
506 * @param string $file The loaded YAML file
508 private static function checkDefinition($id, array $definition, $file)
510 foreach ($definition as $key => $value) {
511 if (!isset(static::$keywords[$key])) {
512 @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('", "', static::$keywords)), E_USER_DEPRECATED);
513 // @deprecated Uncomment the following statement in Symfony 4.0
514 // and also update the corresponding unit test to make it expect
515 // an InvalidArgumentException exception.
516 //throw new InvalidArgumentException(sprintf('The configuration key "%s" is unsupported for service definition "%s" in "%s". Allowed configuration keys are "%s".', $key, $id, $file, implode('", "', static::$keywords)));