JsonHelper   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 26
rs 10
c 0
b 0
f 0
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A decode() 0 16 3
1
<?php
2
3
/**
4
 * Copyright 2016 SURFnet B.V.
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\Stepup\Helper;
20
21
use Surfnet\Stepup\Exception\JsonException;
22
23
final class JsonHelper
24
{
25
    private static array $jsonErrors = [
26
        JSON_ERROR_DEPTH => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
27
        JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
28
        JSON_ERROR_CTRL_CHAR => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
29
        JSON_ERROR_SYNTAX => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
30
        JSON_ERROR_UTF8 => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded',
31
    ];
32
33
    public static function decode(string $json): mixed
34
    {
35
        $data = json_decode($json, true);
36
37
        if (JSON_ERROR_NONE !== json_last_error()) {
38
            $last = json_last_error();
39
40
            $errorMessage = 'Unknown error';
41
            if (array_key_exists($last, self::$jsonErrors)) {
42
                $errorMessage = self::$jsonErrors[$last];
43
            }
44
45
            throw JsonException::withMessage($errorMessage);
46
        }
47
48
        return $data;
49
    }
50
}
51