blob: 5aefba07229f6465a4fd716e4b156bfd5734c58c [file] [log] [blame]
Matthias Andreas Benkard7b2a3a12021-08-16 10:57:25 +02001<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Translation\Loader;
13
14use Symfony\Component\Translation\Exception\InvalidResourceException;
15
16/**
17 * JsonFileLoader loads translations from an json file.
18 *
19 * @author singles
20 */
21class JsonFileLoader extends FileLoader
22{
23 /**
24 * {@inheritdoc}
25 */
26 protected function loadResource(string $resource)
27 {
28 $messages = [];
29 if ($data = file_get_contents($resource)) {
30 $messages = json_decode($data, true);
31
32 if (0 < $errorCode = json_last_error()) {
33 throw new InvalidResourceException('Error parsing JSON: '.$this->getJSONErrorMessage($errorCode));
34 }
35 }
36
37 return $messages;
38 }
39
40 /**
41 * Translates JSON_ERROR_* constant into meaningful message.
42 */
43 private function getJSONErrorMessage(int $errorCode): string
44 {
45 switch ($errorCode) {
46 case \JSON_ERROR_DEPTH:
47 return 'Maximum stack depth exceeded';
48 case \JSON_ERROR_STATE_MISMATCH:
49 return 'Underflow or the modes mismatch';
50 case \JSON_ERROR_CTRL_CHAR:
51 return 'Unexpected control character found';
52 case \JSON_ERROR_SYNTAX:
53 return 'Syntax error, malformed JSON';
54 case \JSON_ERROR_UTF8:
55 return 'Malformed UTF-8 characters, possibly incorrectly encoded';
56 default:
57 return 'Unknown error';
58 }
59 }
60}