No Description

JsonFileLoader.php 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. /**
  15. * JsonFileLoader loads translations from an json file.
  16. *
  17. * @author singles
  18. */
  19. class JsonFileLoader extends ArrayLoader implements LoaderInterface
  20. {
  21. /**
  22. * {@inheritdoc}
  23. */
  24. public function load($resource, $locale, $domain = 'messages')
  25. {
  26. if (!stream_is_local($resource)) {
  27. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  28. }
  29. if (!file_exists($resource)) {
  30. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  31. }
  32. $messages = json_decode(file_get_contents($resource), true);
  33. if (0 < $errorCode = json_last_error()) {
  34. throw new InvalidResourceException(sprintf('Error parsing JSON - %s', $this->getJSONErrorMessage($errorCode)));
  35. }
  36. if (null === $messages) {
  37. $messages = array();
  38. }
  39. $catalogue = parent::load($messages, $locale, $domain);
  40. $catalogue->addResource(new FileResource($resource));
  41. return $catalogue;
  42. }
  43. /**
  44. * Translates JSON_ERROR_* constant into meaningful message.
  45. *
  46. * @param int $errorCode Error code returned by json_last_error() call
  47. *
  48. * @return string Message string
  49. */
  50. private function getJSONErrorMessage($errorCode)
  51. {
  52. switch ($errorCode) {
  53. case JSON_ERROR_DEPTH:
  54. return 'Maximum stack depth exceeded';
  55. case JSON_ERROR_STATE_MISMATCH:
  56. return 'Underflow or the modes mismatch';
  57. case JSON_ERROR_CTRL_CHAR:
  58. return 'Unexpected control character found';
  59. case JSON_ERROR_SYNTAX:
  60. return 'Syntax error, malformed JSON';
  61. case JSON_ERROR_UTF8:
  62. return 'Malformed UTF-8 characters, possibly incorrectly encoded';
  63. default:
  64. return 'Unknown error';
  65. }
  66. }
  67. }