Completed
Pull Request — master (#134)
by Christoffer
02:39
created

IntCoercer::coerce()   C

Complexity

Conditions 8
Paths 7

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 5.7377
c 0
b 0
f 0
cc 8
eloc 12
nc 7
nop 1
1
<?php
2
3
namespace Digia\GraphQL\Type\Coercer;
4
5
use Digia\GraphQL\Error\InvalidTypeException;
6
7
class IntCoercer extends AbstractCoercer
8
{
9
    /**
10
     * @inheritdoc
11
     */
12
    public function coerce($value)
13
    {
14
        if ($value === '') {
15
            throw new InvalidTypeException('Int cannot represent non 32-bit signed integer value: (empty string)');
16
        }
17
18
        if (\is_bool($value)) {
19
            $value = (int)$value;
20
        }
21
22
        if (!\is_int($value) || $value > PHP_INT_MAX || $value < PHP_INT_MIN) {
23
            throw new InvalidTypeException(
24
                \sprintf('Int cannot represent non 32-bit signed integer value: %s', $value)
25
            );
26
        }
27
28
        $intValue   = (int)$value;
29
        $floatValue = (float)$value;
30
31
        if ($floatValue != $intValue || \floor($floatValue) !== $floatValue) {
32
            throw new InvalidTypeException(\sprintf('Int cannot represent non-integer value: %s', $value));
33
        }
34
35
        return $intValue;
36
    }
37
}
38