Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Translation\Loader; Chris@0: Chris@0: use Symfony\Component\Translation\Exception\InvalidResourceException; Chris@0: Chris@0: /** Chris@0: * JsonFileLoader loads translations from an json file. Chris@0: * Chris@0: * @author singles Chris@0: */ Chris@0: class JsonFileLoader extends FileLoader Chris@0: { Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: protected function loadResource($resource) Chris@0: { Chris@17: $messages = []; Chris@0: if ($data = file_get_contents($resource)) { Chris@0: $messages = json_decode($data, true); Chris@0: Chris@0: if (0 < $errorCode = json_last_error()) { Chris@0: throw new InvalidResourceException(sprintf('Error parsing JSON - %s', $this->getJSONErrorMessage($errorCode))); Chris@0: } Chris@0: } Chris@0: Chris@0: return $messages; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Translates JSON_ERROR_* constant into meaningful message. Chris@0: * Chris@0: * @param int $errorCode Error code returned by json_last_error() call Chris@0: * Chris@0: * @return string Message string Chris@0: */ Chris@0: private function getJSONErrorMessage($errorCode) Chris@0: { Chris@0: switch ($errorCode) { Chris@0: case JSON_ERROR_DEPTH: Chris@0: return 'Maximum stack depth exceeded'; Chris@0: case JSON_ERROR_STATE_MISMATCH: Chris@0: return 'Underflow or the modes mismatch'; Chris@0: case JSON_ERROR_CTRL_CHAR: Chris@0: return 'Unexpected control character found'; Chris@0: case JSON_ERROR_SYNTAX: Chris@0: return 'Syntax error, malformed JSON'; Chris@0: case JSON_ERROR_UTF8: Chris@0: return 'Malformed UTF-8 characters, possibly incorrectly encoded'; Chris@0: default: Chris@0: return 'Unknown error'; Chris@0: } Chris@0: } Chris@0: }