YamlFileLoader.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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\Parser as YamlParser;
  14. use Symfony\Component\Yaml\Exception\ParseException;
  15. /**
  16. * YamlFileLoader loads translations from Yaml files.
  17. *
  18. * @author Fabien Potencier <fabien@symfony.com>
  19. */
  20. class YamlFileLoader extends FileLoader
  21. {
  22. private $yamlParser;
  23. /**
  24. * {@inheritdoc}
  25. */
  26. protected function loadResource($resource)
  27. {
  28. if (null === $this->yamlParser) {
  29. if (!class_exists('Symfony\Component\Yaml\Parser')) {
  30. throw new LogicException('Loading translations from the YAML format requires the Symfony Yaml component.');
  31. }
  32. $this->yamlParser = new YamlParser();
  33. }
  34. $prevErrorHandler = set_error_handler(function ($level, $message, $script, $line) use ($resource, &$prevErrorHandler) {
  35. $message = E_USER_DEPRECATED === $level ? preg_replace('/ on line \d+/', ' in "'.$resource.'"$0', $message) : $message;
  36. return $prevErrorHandler ? $prevErrorHandler($level, $message, $script, $line) : false;
  37. });
  38. try {
  39. $messages = $this->yamlParser->parseFile($resource);
  40. } catch (ParseException $e) {
  41. throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $resource), 0, $e);
  42. } finally {
  43. restore_error_handler();
  44. }
  45. return $messages;
  46. }
  47. }