菜谱项目

YamlFileLoader.php 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. 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')) {
  31. throw new LogicException('Loading translations from the YAML format requires the Symfony Yaml component.');
  32. }
  33. $this->yamlParser = new YamlParser();
  34. }
  35. $prevErrorHandler = set_error_handler(function ($level, $message, $script, $line) use ($resource, &$prevErrorHandler) {
  36. $message = E_USER_DEPRECATED === $level ? preg_replace('/ on line \d+/', ' in "'.$resource.'"$0', $message) : $message;
  37. return $prevErrorHandler ? $prevErrorHandler($level, $message, $script, $line) : false;
  38. });
  39. try {
  40. $messages = $this->yamlParser->parse(file_get_contents($resource), Yaml::PARSE_KEYS_AS_STRINGS);
  41. } catch (ParseException $e) {
  42. throw new InvalidResourceException(sprintf('Error parsing YAML, invalid file "%s"', $resource), 0, $e);
  43. } finally {
  44. restore_error_handler();
  45. }
  46. return $messages;
  47. }
  48. }