1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* This file is part of michael-rubel/laravel-value-objects. (https://github.com/michael-rubel/laravel-value-objects) |
7
|
|
|
* |
8
|
|
|
* @link https://github.com/michael-rubel/laravel-value-objects for the canonical source repository |
9
|
|
|
* @copyright Copyright (c) 2022 Michael Rubél. (https://github.com/michael-rubel/) |
10
|
|
|
* @license https://raw.githubusercontent.com/michael-rubel/laravel-value-objects/main/LICENSE.md MIT |
11
|
|
|
*/ |
12
|
|
|
|
13
|
|
|
namespace MichaelRubel\ValueObjects\Collection\Primitive; |
14
|
|
|
|
15
|
|
|
use InvalidArgumentException; |
16
|
|
|
use MichaelRubel\ValueObjects\Concerns\SanitizesNumbers; |
17
|
|
|
use MichaelRubel\ValueObjects\ValueObject; |
18
|
|
|
use PHP\Math\BigNumber\BigNumber; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* "Number" object that represents numeric values. |
22
|
|
|
* |
23
|
|
|
* @author Michael Rubél <[email protected]> |
24
|
|
|
* |
25
|
|
|
* @template TKey of array-key |
26
|
|
|
* @template TValue |
27
|
|
|
* |
28
|
|
|
* @method static static make(int|string $number, int $scale = 2) |
29
|
|
|
* @method static static from(int|string $number, int $scale = 2) |
30
|
|
|
* @method static static makeOrNull(int|string|null $number, int $scale = 2) |
31
|
|
|
* |
32
|
|
|
* @extends ValueObject<TKey, TValue> |
33
|
|
|
*/ |
34
|
|
|
class Number extends ValueObject |
35
|
|
|
{ |
36
|
|
|
use SanitizesNumbers; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @var BigNumber |
40
|
|
|
*/ |
41
|
|
|
protected BigNumber $bigNumber; |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Create a new instance of the value object. |
45
|
|
|
* |
46
|
|
|
* @param int|string $number |
47
|
|
|
* @param int $scale |
48
|
|
|
*/ |
49
|
18 |
|
public function __construct(int|string $number, protected int $scale = 2) |
50
|
|
|
{ |
51
|
18 |
|
if (isset($this->bigNumber)) { |
52
|
1 |
|
throw new InvalidArgumentException(static::IMMUTABLE_MESSAGE); |
53
|
|
|
} |
54
|
|
|
|
55
|
18 |
|
$this->bigNumber = new BigNumber( |
56
|
18 |
|
$this->sanitize($number), $this->scale, mutable: false |
57
|
|
|
); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Get the object value. |
62
|
|
|
* |
63
|
|
|
* @return string |
64
|
|
|
*/ |
65
|
11 |
|
public function value(): string |
66
|
|
|
{ |
67
|
11 |
|
return $this->bigNumber->getValue(); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* Get the number as an integer. |
72
|
|
|
* |
73
|
|
|
* @return int |
74
|
|
|
*/ |
75
|
1 |
|
public function asInteger(): int |
76
|
|
|
{ |
77
|
1 |
|
return (int) $this->bigNumber->getValue(); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Get the number as a float. |
82
|
|
|
* |
83
|
|
|
* @return float |
84
|
|
|
*/ |
85
|
1 |
|
public function asFloat(): float |
86
|
|
|
{ |
87
|
1 |
|
return (float) $this->bigNumber->getValue(); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|