AnyScalarType::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace TheCodingMachine\GraphQLite\Types\AnyScalar;
5
6
7
use Exception;
8
use GraphQL\Error\Error;
9
use GraphQL\Language\AST\BooleanValueNode;
10
use GraphQL\Language\AST\FloatValueNode;
11
use GraphQL\Language\AST\IntValueNode;
12
use GraphQL\Language\AST\Node;
13
use GraphQL\Language\AST\StringValueNode;
14
use GraphQL\Type\Definition\ScalarType;
15
use GraphQL\Utils\Utils;
16
17
final class AnyScalarType extends ScalarType
18
{
19
    public const NAME = 'AnyScalar';
20
21
    /**
22
     * @var self
23
     */
24
    private static $instance;
25
26
    public function __construct()
27
    {
28
        parent::__construct([
29
            'name' => 'AnyScalar',
30
            'description' => 'A GraphQL type that can contain any scalar value (int, string, bool or float)'
31
        ]);
32
    }
33
34
    public static function getInstance(): self
35
    {
36
        if (self::$instance === null) {
37
            self::$instance = new self();
38
        }
39
        return self::$instance;
40
    }
41
42
    /**
43
     * Serializes an internal value to include in a response.
44
     *
45
     * @param string $value
46
     * @return string
47
     */
48
    public function serialize($value)
49
    {
50
        return $value;
51
    }
52
53
    /**
54
     * Parses an externally provided value (query variable) to use as an input
55
     *
56
     * @param mixed $value
57
     * @return mixed
58
     */
59
    public function parseValue($value)
60
    {
61
        if (!is_scalar($value)) {
62
            throw new Error('Cannot represent following value as scalar: ' . Utils::printSafeJson($value));
63
        }
64
65
        return $value;
66
    }
67
68
    /**
69
     * Parses an externally provided literal value (hardcoded in GraphQL query) to use as an input
70
     *
71
     * In the case of an invalid node or value this method must throw an Exception
72
     *
73
     * @param Node         $valueNode
74
     * @param mixed[]|null $variables
75
     *
76
     * @return mixed
77
     *
78
     * @throws Exception
79
     */
80
    public function parseLiteral($valueNode, ?array $variables = null)
81
    {
82
        if ($valueNode instanceof StringValueNode || $valueNode instanceof BooleanValueNode) {
83
            return $valueNode->value;
84
        }
85
        if ($valueNode instanceof IntValueNode) {
86
            return (int) $valueNode->value;
87
        }
88
        if ($valueNode instanceof FloatValueNode) {
89
            return (float) $valueNode->value;
90
        }
91
92
        throw new Error('Not a valid scalar', $valueNode);
93
    }
94
}
95