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

StringType::coerceString()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
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\Node;
10
use GraphQL\Language\AST\StringValueNode;
11
use GraphQL\Utils\Utils;
12
use function is_array;
13
use function is_object;
14
use function is_scalar;
15
use function is_string;
16
use function method_exists;
17
18
class StringType extends ScalarType
19
{
20
    /** @var string */
21
    public $name = Type::STRING;
22
23
    /** @var string */
24
    public $description =
25
        'The `String` scalar type represents textual data, represented as UTF-8
26
character sequences. The String type is most often used by GraphQL to
27
represent free-form human-readable text.';
28
29
    /**
30
     * @param mixed $value
31
     *
32
     * @return mixed|string
33
     *
34
     * @throws Error
35
     */
36 141
    public function serialize($value)
37
    {
38 141
        $canCast = is_scalar($value)
39 3
            || (is_object($value) && method_exists($value, '__toString'))
40 141
            || $value === null;
41
42 141
        if (! $canCast) {
43 2
            throw new Error(
44 2
                'String cannot represent value: ' . Utils::printSafe($value)
45
            );
46
        }
47
48 139
        return (string) $value;
49
    }
50
51
    /**
52
     * @param mixed $value
53
     *
54
     * @return string
55
     *
56
     * @throws Error
57
     */
58 23
    public function parseValue($value)
59
    {
60 23
        if (! is_string($value)) {
61 2
            throw new Error(
62 2
                'String cannot represent a non string value: ' . Utils::printSafe($value)
63
            );
64
        }
65
66 21
        return $value;
67
    }
68
69
    /**
70
     * @param Node         $valueNode
71
     * @param mixed[]|null $variables
72
     *
73
     * @return string|null
74
     *
75
     * @throws Exception
76
     */
77 62
    public function parseLiteral($valueNode, ?array $variables = null)
78
    {
79 62
        if ($valueNode instanceof StringValueNode) {
80 53
            return $valueNode->value;
81
        }
82
83
        // Intentionally without message, as all information already in wrapped Exception
84 12
        throw new Exception();
85
    }
86
}
87