YamlFileLoader.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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\Translation\Loader;
  11. use Symfony\Component\Translation\Exception\InvalidResourceException;
  12. use Symfony\Component\Translation\Exception\LogicException;
  13. use Symfony\Component\Yaml\Exception\ParseException;
  14. use Symfony\Component\Yaml\Parser as YamlParser;
  15. use Symfony\Component\Yaml\Yaml;
  16. /**
  17. * YamlFileLoader loads translations from Yaml files.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class YamlFileLoader extends FileLoader
  22. {
  23. private $yamlParser;
  24. /**
  25. * {@inheritdoc}
  26. */
  27. protected function loadResource($resource)
  28. {
  29. if (null === $this->yamlParser) {
  30. if (!class_exists(\Symfony\Component\Yaml\Parser::class)) {
  31. throw new LogicException('Loading translations from the YAML format requires the Symfony Yaml component.');
  32. }
  33. $this->yamlParser = new YamlParser();
  34. }
  35. try {
  36. $messages = $this->yamlParser->parseFile($resource, Yaml::PARSE_CONSTANT);
  37. } catch (ParseException $e) {
  38. throw new InvalidResourceException(sprintf('The file "%s" does not contain valid YAML: ', $resource).$e->getMessage(), 0, $e);
  39. }
  40. if (null !== $messages && !\is_array($messages)) {
  41. throw new InvalidResourceException(sprintf('Unable to load file "%s".', $resource));
  42. }
  43. return $messages ?: [];
  44. }
  45. }