Completed
Pull Request — master (#134)
by Christoffer
04:35
created

IntCoercer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
dl 0
loc 29
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
C coerce() 0 24 8
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