NumberTag::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 4
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 3
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Jasny\PhpdocParser\Tag;
6
7
use Jasny\PhpdocParser\PhpdocException;
8
9
use function Jasny\expect_type;
10
11
/**
12
 * Only use the first word (that should be a number) after the tag, ignoring the rest
13
 */
14
class NumberTag extends AbstractTag
15
{
16
    /**
17
     * @var string
18
     */
19
    protected $type;
20
21
    /**
22
     * @var int|float
23
     */
24
    protected $min;
25
26
    /**
27
     * @var int|float
28
     */
29
    protected $max;
30
31
    /**
32
     * NumberTag constructor.
33
     *
34
     * @param string    $name
35
     * @param string    $type  ('int', 'float')
36
     * @param int|float $min
37
     * @param int|float $max
38
     */
39 33
    public function __construct(string $name, string $type = 'int', $min = 0, $max = INF)
40
    {
41 33
        if (!in_array($type, ['int', 'integer', 'float'], true)) {
42 1
            throw new PhpdocException("NumberTag should be of type int or float, $type given");
43
        }
44
45 32
        expect_type($min, ['int', 'float']);
46 31
        expect_type($max, ['int', 'float']);
47
48 30
        if ($min > $max) {
49 1
            throw new PhpdocException("Min value (given $min) should be less than max (given $max)");
50
        }
51
52 29
        parent::__construct($name);
53
54 29
        $this->type = $type;
55 29
        $this->min = $min;
56 29
        $this->max = $max;
57
    }
58
59
    /**
60
     * Process an notation.
61
     *
62
     * @param array  $notations
63
     * @param string $value
64
     * @return array
65
     */
66 10
    public function process(array $notations, string $value): array
67
    {
68 10
        [$word] = explode(' ', $value, 2);
69
70 10
        if (!is_numeric($word)) {
71 3
            throw new PhpdocException("Failed to parse '@{$this->name} $word': not a number");
72
        }
73
74 7
        if ($word < $this->min) {
75 1
            throw new PhpdocException("Parsed value $word should be greater then min value {$this->min}");
76
        }
77
78 6
        if ($word > $this->max) {
79 1
            throw new PhpdocException("Parsed value $word should be less then max value {$this->max}");
80
        }
81
82 5
        if (in_array($this->type, ['int', 'integer'], true)) {
83 2
            $word = (int)$word;
84
        }
85
86 5
        $notations[$this->name] = $word + 0;
87
88 5
        return $notations;
89
    }
90
}
91