Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
50.00% covered (danger)
50.00%
1 / 2
CRAP
61.54% covered (warning)
61.54%
8 / 13
JsonFileLoader
0.00% covered (danger)
0.00%
0 / 1
50.00% covered (danger)
50.00%
1 / 2
15.69
61.54% covered (warning)
61.54%
8 / 13
 loadResource
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
6 / 6
 getJSONErrorMessage
0.00% covered (danger)
0.00%
0 / 1
24.86
28.57% covered (danger)
28.57%
2 / 7
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
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($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}