YamlFileLoader.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 $yamlParser;
  24. protected function loadResource(string $resource): array
  25. {
  26. if (!isset($this->yamlParser)) {
  27. if (!class_exists(\Symfony\Component\Yaml\Parser::class)) {
  28. throw new LogicException('Loading translations from the YAML format requires the Symfony Yaml component.');
  29. }
  30. $this->yamlParser = new YamlParser();
  31. }
  32. try {
  33. $messages = $this->yamlParser->parseFile($resource, Yaml::PARSE_CONSTANT);
  34. } catch (ParseException $e) {
  35. throw new InvalidResourceException(sprintf('The file "%s" does not contain valid YAML: ', $resource).$e->getMessage(), 0, $e);
  36. }
  37. if (null !== $messages && !\is_array($messages)) {
  38. throw new InvalidResourceException(sprintf('Unable to load file "%s".', $resource));
  39. }
  40. return $messages ?: [];
  41. }
  42. }