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

FloatType::coerceFloat()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 9.6111
c 0
b 0
f 0
cc 5
nc 3
nop 1
crap 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A FloatType::serialize() 0 12 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\FloatValueNode;
10
use GraphQL\Language\AST\IntValueNode;
11
use GraphQL\Language\AST\Node;
12
use GraphQL\Utils\Utils;
13
use function floatval;
14
use function is_array;
15
use function is_bool;
16
use function is_finite;
17
use function is_float;
18
use function is_int;
19
use function is_nan;
20
use function is_numeric;
21
use function sprintf;
22
23
class FloatType extends ScalarType
24
{
25
    /** @var string */
26
    public $name = Type::FLOAT;
27
28
    /** @var string */
29
    public $description =
30
        'The `Float` scalar type represents signed double-precision fractional
31
values as specified by
32
[IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point). ';
33
34
    /**
35
     * @param mixed $value
36
     *
37
     * @return float|null
38
     *
39
     * @throws Error
40
     */
41 8
    public function serialize($value)
42
    {
43 8
        $float = is_numeric($value) || is_bool($value) ? floatval($value) : null;
44
45 8
        if ($float === null || ! is_finite($float)) {
46 5
            throw new Error(
47
                'Float cannot represent non numeric value: ' .
48 5
                Utils::printSafe($value)
49
            );
50
        }
51
52 3
        return $float;
53
    }
54
55
    /**
56
     * @param mixed $value
57
     *
58
     * @return float|null
59
     *
60
     * @throws Error
61
     */
62 10
    public function parseValue($value)
63
    {
64 10
        $float = is_float($value) || is_int($value) ? floatval($value) : null;
65
66 10
        if ($float === null || ! is_finite($float)) {
67 6
            throw new Error(
68
                'Float cannot represent non numeric value: ' .
69 6
                Utils::printSafe($value)
70
            );
71
        }
72
73 4
        return $float;
74
    }
75
76
    /**
77
     * @param Node         $valueNode
78
     * @param mixed[]|null $variables
79
     *
80
     * @return float|null
81
     *
82
     * @throws Exception
83
     */
84 8
    public function parseLiteral($valueNode, ?array $variables = null)
85
    {
86 8
        if ($valueNode instanceof FloatValueNode || $valueNode instanceof IntValueNode) {
87 4
            return (float) $valueNode->value;
88
        }
89
90
        // Intentionally without message, as all information already in wrapped Exception
91 4
        throw new Exception();
92
    }
93
}
94