1 | <?php declare(strict_types=1); |
||
2 | /** |
||
3 | * This file is part of the daikon-cqrs/value-object project. |
||
4 | * |
||
5 | * For the full copyright and license information, please view the LICENSE |
||
6 | * file that was distributed with this source code. |
||
7 | */ |
||
8 | |||
9 | namespace Daikon\ValueObject; |
||
10 | |||
11 | use Daikon\Interop\Assertion; |
||
12 | use Daikon\Interop\MakeEmptyInterface; |
||
13 | |||
14 | final class FloatValue implements MakeEmptyInterface, ValueObjectInterface |
||
15 | { |
||
16 | private ?float $value; |
||
17 | |||
18 | /** @param null|int|float $value */ |
||
19 | 10 | public static function fromNative($value): self |
|
20 | { |
||
21 | 10 | if (is_integer($value)) { |
|
22 | 3 | $value = floatval($value); |
|
23 | } |
||
24 | 10 | Assertion::nullOrFloat($value, 'Trying to create FloatValue VO from unsupported value type.'); |
|
25 | 10 | return $value === null ? new self : new self(floatval($value)); |
|
26 | } |
||
27 | |||
28 | 2 | public static function zero(): self |
|
29 | { |
||
30 | 2 | return new self(0.0); |
|
31 | } |
||
32 | |||
33 | 2 | public static function makeEmpty(): self |
|
34 | { |
||
35 | 2 | return new self; |
|
36 | } |
||
37 | |||
38 | 1 | public function format(int $decimals = 0, string $point = '.', string $separator = ','): string |
|
39 | { |
||
40 | 1 | $this->assertNotEmpty(); |
|
41 | 1 | return number_format($this->value, $decimals, $point, $separator); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
42 | } |
||
43 | |||
44 | 3 | public function isEmpty(): bool |
|
45 | { |
||
46 | 3 | return $this->value === null; |
|
47 | } |
||
48 | |||
49 | 1 | public function isZero(): bool |
|
50 | { |
||
51 | 1 | $this->assertNotEmpty(); |
|
52 | 1 | return $this->value === 0.0; |
|
53 | } |
||
54 | |||
55 | 6 | public function toNative(): ?float |
|
56 | { |
||
57 | 6 | return $this->value; |
|
58 | } |
||
59 | |||
60 | /** @param self $comparator */ |
||
61 | 1 | public function equals($comparator): bool |
|
62 | { |
||
63 | 1 | Assertion::isInstanceOf($comparator, self::class); |
|
64 | 1 | return $this->toNative() === $comparator->toNative(); |
|
65 | } |
||
66 | |||
67 | 1 | public function __toString(): string |
|
68 | { |
||
69 | 1 | return (string)$this->value; |
|
70 | } |
||
71 | |||
72 | 2 | private function assertNotEmpty(): void |
|
73 | { |
||
74 | 2 | Assertion::false($this->isEmpty(), 'Float is empty.'); |
|
75 | 2 | } |
|
76 | |||
77 | 10 | private function __construct(?float $value = null) |
|
78 | { |
||
79 | 10 | $this->value = $value; |
|
80 | 10 | } |
|
81 | } |
||
82 |