暂无描述

JsonFileLoader.php 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. /**
  13. * JsonFileLoader loads translations from an json file.
  14. *
  15. * @author singles
  16. */
  17. class JsonFileLoader extends FileLoader
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. protected function loadResource($resource)
  23. {
  24. $messages = [];
  25. if ($data = file_get_contents($resource)) {
  26. $messages = json_decode($data, true);
  27. if (0 < $errorCode = json_last_error()) {
  28. throw new InvalidResourceException('Error parsing JSON: '.$this->getJSONErrorMessage($errorCode));
  29. }
  30. }
  31. return $messages;
  32. }
  33. /**
  34. * Translates JSON_ERROR_* constant into meaningful message.
  35. */
  36. private function getJSONErrorMessage(int $errorCode): string
  37. {
  38. switch ($errorCode) {
  39. case \JSON_ERROR_DEPTH:
  40. return 'Maximum stack depth exceeded';
  41. case \JSON_ERROR_STATE_MISMATCH:
  42. return 'Underflow or the modes mismatch';
  43. case \JSON_ERROR_CTRL_CHAR:
  44. return 'Unexpected control character found';
  45. case \JSON_ERROR_SYNTAX:
  46. return 'Syntax error, malformed JSON';
  47. case \JSON_ERROR_UTF8:
  48. return 'Malformed UTF-8 characters, possibly incorrectly encoded';
  49. default:
  50. return 'Unknown error';
  51. }
  52. }
  53. }