Completed
Push — main ( fffb13...d8afdd )
by Laurent
139:07 queued 124:29
created

Taxes::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Domain\Model\Common\Entities;
6
7
use NumberFormatter;
8
9
class Taxes
10
{
11
    /**
12
     * @var float
13
     */
14
    private $rate;
15
16
    /**
17
     * @var false|string
18
     */
19
    private $name;
20
21
    /**
22
     * Taxes constructor.
23
     *
24
     * @param float $rate
25
     */
26
    public function __construct(float $rate)
27
    {
28
        $fmtPercent = new NumberFormatter('fr_FR', NumberFormatter::PERCENT);
29
        $fmtPercent->setAttribute($fmtPercent::FRACTION_DIGITS, 2);
30
31
        $this->rate = $rate / 100;
32
33
        $fraction = explode('.', (string) $rate);
34
        if (strlen($fraction[1]) > 2) {
35
            $this->rate = $rate;
36
        }
37
38
        $this->name = $fmtPercent->format($this->rate);
39
    }
40
41
    public static function fromFloat(float $rate): self
42
    {
43
        return new self($rate);
44
    }
45
46
    public static function fromPercent(string $name): self
47
    {
48
        preg_match('/^([0-9]*)(,([0-9]*?)) %$/', trim($name), $str);
49
        $float = $str[1].'.'.$str[3];
50
51
        return new self((float) $float);
52
    }
53
54
    final public function rate(): float
55
    {
56
        return $this->rate;
57
    }
58
59
    final public function name(): string
60
    {
61
        return $this->name;
62
    }
63
}
64