JsonDecode   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 10
c 1
b 0
f 0
dl 0
loc 31
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 10 2
A getJsonErrorMsg() 0 10 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Koriym\AppStateDiagram;
6
7
use Seld\JsonLint\JsonParser;
8
use Seld\JsonLint\ParsingException;
9
use UnexpectedValueException;
10
11
use function assert;
12
use function defined;
13
use function is_object;
14
use function json_decode;
15
use function json_last_error;
16
17
use const JSON_ERROR_UTF8;
18
19
final class JsonDecode
20
{
21
    public function __invoke(string $jsonString): object
22
    {
23
        $json = json_decode($jsonString, false);
24
        if (json_last_error()) {
25
            throw $this->getJsonErrorMsg($jsonString);
26
        }
27
28
        assert(is_object($json));
29
30
        return $json;
31
    }
32
33
    /**
34
     * Better json error message
35
     *
36
     * Taken from [how Composer uses this library] in https://github.com/Seldaek/jsonlint
37
     *
38
     * @see https://github.com/composer/composer/blob/56edd53046fd697d32b2fd2fbaf45af5d7951671/src/Composer/Json/JsonFile.php#L283-L318
39
     */
40
    private function getJsonErrorMsg(string $json): ParsingException
41
    {
42
        $result = (new JsonParser())->lint($json);
43
        if (defined('JSON_ERROR_UTF8') && json_last_error() === JSON_ERROR_UTF8) {
44
            throw new UnexpectedValueException('"' . $json . '" is not UTF-8, could not parse as JSON');
45
        }
46
47
        assert($result instanceof ParsingException);
48
49
        return new ParsingException($result->getMessage(), $result->getDetails());
50
    }
51
}
52