Passed
Pull Request — master (#55)
by Tim
02:09
created

IntegerValue::toInteger()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\XML\Type;
6
7
use SimpleSAML\XML\Assert\Assert;
8
use SimpleSAML\XML\Exception\{RuntimeException, SchemaViolationException};
9
10
use function bccomp;
11
use function intval;
12
use function strval;
13
14
/**
15
 * @package simplesaml/xml-common
16
 */
17
class IntegerValue extends DecimalValue
18
{
19
    /** @var string */
20
    public const SCHEMA_TYPE = 'integer';
21
22
23
    /**
24
     * Validate the value.
25
     *
26
     * @param string $value
27
     * @throws \SimpleSAML\XML\Exception\SchemaViolationException on failure
28
     * @return void
29
     */
30
    protected function validateValue(string $value): void
31
    {
32
        Assert::validInteger($this->sanitizeValue($value), SchemaViolationException::class);
33
    }
34
35
36
    /**
37
     * Convert from integer
38
     *
39
     * @param int $value
40
     * @return static
41
     */
42
    public static function fromInteger(int $value): static
43
    {
44
        return new static(strval($value));
45
    }
46
47
48
    /**
49
     * Convert to integer
50
     *
51
     * @return int
52
     */
53
    public function toInteger(): int
54
    {
55
        $value = $this->getValue();
56
57
        if (bccomp($value, strval(PHP_INT_MAX)) === 1) {
58
            throw new RuntimeException("Cannot convert to integer: out of bounds.");
59
        }
60
61
        return intval($value);
62
    }
63
}
64