YamlFileLoader.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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\NotFoundResourceException;
  13. use Symfony\Component\Config\Resource\FileResource;
  14. use Symfony\Component\Yaml\Parser as YamlParser;
  15. use Symfony\Component\Yaml\Exception\ParseException;
  16. /**
  17. * YamlFileLoader loads translations from Yaml files.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. *
  21. * @api
  22. */
  23. class YamlFileLoader extends ArrayLoader implements LoaderInterface
  24. {
  25. private $yamlParser;
  26. /**
  27. * {@inheritdoc}
  28. *
  29. * @api
  30. */
  31. public function load($resource, $locale, $domain = 'messages')
  32. {
  33. if (!stream_is_local($resource)) {
  34. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  35. }
  36. if (!file_exists($resource)) {
  37. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  38. }
  39. if (null === $this->yamlParser) {
  40. $this->yamlParser = new YamlParser();
  41. }
  42. try {
  43. $messages = $this->yamlParser->parse(file_get_contents($resource));
  44. } catch (ParseException $e) {
  45. throw new InvalidResourceException('Error parsing YAML.', 0, $e);
  46. }
  47. // empty file
  48. if (null === $messages) {
  49. $messages = array();
  50. }
  51. // not an array
  52. if (!is_array($messages)) {
  53. throw new InvalidResourceException(sprintf('The file "%s" must contain a YAML array.', $resource));
  54. }
  55. $catalogue = parent::load($messages, $locale, $domain);
  56. $catalogue->addResource(new FileResource($resource));
  57. return $catalogue;
  58. }
  59. }