JsonFileLoader.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. protected function loadResource(string $resource): array
  20. {
  21. $messages = [];
  22. if ($data = file_get_contents($resource)) {
  23. $messages = json_decode($data, true);
  24. if (0 < $errorCode = json_last_error()) {
  25. throw new InvalidResourceException('Error parsing JSON: '.$this->getJSONErrorMessage($errorCode));
  26. }
  27. }
  28. return $messages;
  29. }
  30. /**
  31. * Translates JSON_ERROR_* constant into meaningful message.
  32. */
  33. private function getJSONErrorMessage(int $errorCode): string
  34. {
  35. return match ($errorCode) {
  36. \JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
  37. \JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
  38. \JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  39. \JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
  40. \JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
  41. default => 'Unknown error',
  42. };
  43. }
  44. }