Failed Conditions
Push — master ( 4252f4...9d8e13 )
by Adrien
07:13
created

AbstractStringBasedType::serialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Api\Scalar;
6
7
use GraphQL\Error\Error;
8
use GraphQL\Language\AST\Node;
9
use GraphQL\Language\AST\StringValueNode;
10
use GraphQL\Type\Definition\ScalarType;
11
use GraphQL\Utils\Utils;
12
13
abstract class AbstractStringBasedType extends ScalarType
14
{
15
    /**
16
     * Validate value
17
     *
18
     * @param mixed $value
19
     *
20
     * @return bool
21
     */
22
    abstract protected function isValid($value): bool;
23
24
    /**
25
     * Serializes an internal value to include in a response.
26
     *
27
     * @param mixed $value
28
     *
29
     * @return mixed
30
     */
31 13
    public function serialize($value)
32
    {
33
        // Assuming internal representation of url is always correct:
34 13
        return $value;
35
    }
36
37
    /**
38
     * Parses an externally provided value (query variable) to use as an input
39
     *
40
     * @param mixed $value
41
     *
42
     * @return mixed
43
     */
44 13
    public function parseValue($value)
45
    {
46 13
        if (!$this->isValid($value)) {
47 7
            throw new \UnexpectedValueException('Query error: Not a valid ' . $this->name . ': ' . Utils::printSafe($value));
48
        }
49
50 6
        return $value;
51
    }
52
53
    /**
54
     * Parses an externally provided literal value to use as an input (e.g. in Query AST)
55
     *
56
     * @param $ast Node
57
     * @param null|array $variables
58
     *
59
     * @return null|string
60
     */
61 16
    public function parseLiteral($ast, array $variables = null)
62
    {
63
        // Note: throwing GraphQL\Error\Error vs \UnexpectedValueException to benefit from GraphQL
64
        // error location in query:
65 16
        if (!($ast instanceof StringValueNode)) {
66
            throw new Error('Query error: Can only parse strings got: ' . $ast->kind, [$ast]);
67
        }
68
69 16
        if (!$this->isValid($ast->value)) {
70 7
            throw new Error('Query error: Not a valid ' . $this->name, [$ast]);
71
        }
72
73 9
        return $ast->value;
74
    }
75
}
76