Passed
Pull Request — master (#12)
by Ivo
02:52
created

JSONScalarType::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 3
c 1
b 0
f 1
nc 2
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
namespace TheCodingMachine\GraphQLite\Types\JSONScalar;
4
5
use Exception;
6
use GraphQL\Error\Error;
7
use GraphQL\Type\Definition\ScalarType;
8
use GraphQL\Utils\Utils as GraphQLUtils;
9
10
final class JSONScalarType extends ScalarType
11
{
12
    public const NAME = 'JSON';
13
14
    /**
15
     * @var self
16
     */
17
    private static $instance;
18
19
    public function __construct()
20
    {
21
        parent::__construct([
22
            'name' => 'JSON',
23
            'description' => 'A GraphQL type that can contain json'
24
        ]);
25
    }
26
27
    public static function getInstance(): self
28
    {
29
        if (self::$instance === null) {
30
            self::$instance = new self();
31
        }
32
        return self::$instance;
33
    }
34
35
    /**
36
     * @param mixed $value
37
     * @return mixed
38
     */
39
    public function serialize($value)
40
    {
41
        return $value;
42
    }
43
44
    /**
45
     * @param mixed $value
46
     * @return mixed
47
     * @throws Error
48
     */
49
    public function parseValue($value)
50
    {
51
        return $this->decodeJSON($value);
52
    }
53
54
    /**
55
     * @param mixed $valueNode
56
     * @param mixed[]|null $variables
57
     * @return mixed
58
     * @throws Exception
59
     */
60
    public function parseLiteral($valueNode, ?array $variables = null)
61
    {
62
        if (!property_exists($valueNode, 'value')) {
63
            throw new Error(
64
                'Can only parse literals that contain a value, got '.GraphQLUtils::printSafeJson($valueNode)
65
            );
66
        }
67
68
        return $this->decodeJSON($valueNode->value);
69
    }
70
71
    /**
72
     *
73
     * @param mixed $value
74
     * @throws Error
75
     * @return mixed
76
     */
77
    private function decodeJSON($value)
78
    {
79
        $decoded = is_string($value) ? json_decode($value, true) : $value;
80
        if ($decoded === null) {
81
            throw new Error(
82
                'Error decoding JSON '. GraphQLUtils::printSafeJson($value)
83
            );
84
        }
85
86
        return $decoded;
87
    }
88
}
89