Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 1 | <?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 | |
| 12 | namespace Symfony\Component\Translation\Loader; |
| 13 | |
| 14 | use Symfony\Component\Translation\Exception\InvalidResourceException; |
| 15 | |
| 16 | /** |
| 17 | * JsonFileLoader loads translations from an json file. |
| 18 | * |
| 19 | * @author singles |
| 20 | */ |
| 21 | class JsonFileLoader extends FileLoader |
| 22 | { |
| 23 | /** |
| 24 | * {@inheritdoc} |
| 25 | */ |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 26 | protected function loadResource(string $resource): array |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 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 | } |