Passed
Push — master ( a27dd3...975c9f )
by Vladimir
11:24
created

IDType::serialize()   A

Complexity

Conditions 5
Paths 10

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.6111
c 0
b 0
f 0
cc 5
nc 10
nop 1
crap 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQL\Type\Definition;
6
7
use Exception;
8
use GraphQL\Error\Error;
9
use GraphQL\Language\AST\IntValueNode;
10
use GraphQL\Language\AST\Node;
11
use GraphQL\Language\AST\StringValueNode;
12
use GraphQL\Utils\Utils;
13
use function is_array;
14
use function is_int;
15
use function is_object;
16
use function is_scalar;
17
use function is_string;
18
use function method_exists;
19
20
class IDType extends ScalarType
21
{
22
    /** @var string */
23
    public $name = 'ID';
24
25
    /** @var string */
26
    public $description =
27
        'The `ID` scalar type represents a unique identifier, often used to
28
refetch an object or as key for a cache. The ID type appears in a JSON
29
response as a String; however, it is not intended to be human-readable.
30
When expected as an input type, any string (such as `"4"`) or integer
31
(such as `4`) input value will be accepted as an ID.';
32
33
    /**
34
     * @param mixed $value
35
     *
36
     * @return string
37
     *
38
     * @throws Error
39
     */
40 8
    public function serialize($value)
41
    {
42 8
        $canCast = is_string($value)
43 8
            || is_int($value)
44 8
            || (is_object($value) && method_exists($value, '__toString'));
45
46 8
        if (! $canCast) {
47 5
            throw new Error('ID cannot represent value: ' . Utils::printSafe($value));
48
        }
49
50 3
        return (string) $value;
51
    }
52
53
    /**
54
     * @param mixed $value
55
     *
56
     * @return string
57
     *
58
     * @throws Error
59
     */
60 4
    public function parseValue($value)
61
    {
62 4
        if (is_string($value) || is_int($value)) {
63 1
            return (string) $value;
64
        }
65 3
        throw new Error('ID cannot represent value: ' . Utils::printSafe($value));
66
    }
67
68
    /**
69
     * @param Node         $valueNode
70
     * @param mixed[]|null $variables
71
     *
72
     * @return string|null
73
     *
74
     * @throws Exception
75
     */
76 8
    public function parseLiteral($valueNode, ?array $variables = null)
77
    {
78 8
        if ($valueNode instanceof StringValueNode || $valueNode instanceof IntValueNode) {
79 4
            return $valueNode->value;
80
        }
81
82
        // Intentionally without message, as all information already in wrapped Exception
83 4
        throw new Exception();
84
    }
85
}
86