IntType::asInt()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tdn\PhpTypes\Type;
6
7
use Tdn\PhpTypes\Exception\InvalidTypeCastException;
8
use Tdn\PhpTypes\Math\MathAdapterInterface;
9
10
/**
11
 * Class IntType.
12
 *
13
 * A IntType is a TypeInterface implementation that wraps around a regular PHP int.
14
 *
15
 * {@inheritdoc}
16
 */
17
class IntType extends AbstractNumberType
18
{
19
    /**
20
     * @param int                       $int
21
     * @param MathAdapterInterface|null $mathAdapter
22
     */
23 39
    public function __construct(int $int, MathAdapterInterface $mathAdapter = null)
24
    {
25 39
        parent::__construct($int, 0, $mathAdapter);
26 39
    }
27
28
    /**
29
     * {@inheritdoc}
30
     *
31
     * @return string|float|int
32
     */
33 3
    public function __invoke(int $toType = Type::INT)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
34
    {
35
        switch ($toType) {
36 3
            case Type::INT:
37 1
                return $this->value;
38 3
            case Type::FLOAT:
39 1
                return (float) $this->get();
40 3
            case Type::STRING:
41 1
                return (string) $this->get();
42
            default:
43 2
                throw new InvalidTypeCastException(static::class, $this->getTranslatedType($toType));
44
        }
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     *
50
     * @return IntType
51
     */
52 27
    public static function valueOf($mixed, int $precision = null): IntType
53
    {
54
        //Dealing with big integers. Best to use FloatType.
55 27
        if (is_numeric($mixed) && ($mixed >= PHP_INT_MAX && !ctype_digit($mixed))) {
56 1
            throw new \RuntimeException('Incorrect type used. Use FloatType instead.');
57
        }
58
59 26
        return new static(self::asInt($mixed));
60
    }
61
62
    /**
63
     * Returns a mixed variable as a int.
64
     *
65
     * @param mixed $mixed
66
     *
67
     * @return int
68
     */
69 26
    private static function asInt($mixed): int
70
    {
71 26
        return static::asSubType(
72 26
            function ($v) {
73 19
                return intval(round($v));
74 26
            },
75 26
            $mixed
76
        );
77
    }
78
}
79