Completed
Push — master ( ace74a...38a91c )
by Daan van
04:54
created

JsonHelper::decode()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 29
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
rs 8.5806
cc 4
eloc 17
nc 4
nop 1
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\InvalidArgumentException;
22
use Surfnet\Stepup\Exception\JsonException;
23
24
final class JsonHelper
25
{
26
    public static function decode($json)
27
    {
28
        if (!is_string($json)) {
29
            throw InvalidArgumentException::invalidType('string', 'json', $json);
30
        }
31
32
        static $jsonErrors = [
33
            JSON_ERROR_DEPTH          => 'JSON_ERROR_DEPTH - Maximum stack depth exceeded',
34
            JSON_ERROR_STATE_MISMATCH => 'JSON_ERROR_STATE_MISMATCH - Underflow or the modes mismatch',
35
            JSON_ERROR_CTRL_CHAR      => 'JSON_ERROR_CTRL_CHAR - Unexpected control character found',
36
            JSON_ERROR_SYNTAX         => 'JSON_ERROR_SYNTAX - Syntax error, malformed JSON',
37
            JSON_ERROR_UTF8           => 'JSON_ERROR_UTF8 - Malformed UTF-8 characters, possibly incorrectly encoded',
38
        ];
39
40
        $data = json_decode($json, true);
41
42
        if (JSON_ERROR_NONE !== json_last_error()) {
43
            $last         = json_last_error();
44
            $errorMessage = $jsonErrors[$last];
45
46
            if (!isset($errorMessage)) {
47
                $errorMessage = 'Unknown error';
48
            }
49
50
            throw JsonException::withMessage($errorMessage);
51
        }
52
53
        return $data;
54
    }
55
}
56