Completed
Push — master ( e51596...c1a62f )
by Vladimir
03:52
created

StringType::parseValue()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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