|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Asika\UnitConverter\Concerns; |
| 6 | + |
| 7 | +use Brick\Math\BigDecimal; |
| 8 | +use Brick\Math\BigNumber; |
| 9 | +use Brick\Math\RoundingMode; |
| 10 | + |
| 11 | +trait CalculationTrait |
| 12 | +{ |
| 13 | + public function plus( |
| 14 | + BigNumber|int|float|string|self $that, |
| 15 | + ?int $scale = null, |
| 16 | + RoundingMode $roundingMode = RoundingMode::UNNECESSARY, |
| 17 | + ): static { |
| 18 | + $new = clone $this; |
| 19 | + $new->value = $new->value->plus($this->preprocessThat($that, $scale, $roundingMode)); |
| 20 | + |
| 21 | + return $new; |
| 22 | + } |
| 23 | + |
| 24 | + public function minus( |
| 25 | + BigNumber|int|float|string|self $that, |
| 26 | + ?int $scale = null, |
| 27 | + RoundingMode $roundingMode = RoundingMode::UNNECESSARY, |
| 28 | + ): static { |
| 29 | + $new = clone $this; |
| 30 | + $new->value = $new->value->minus($this->preprocessThat($that, $scale, $roundingMode)); |
| 31 | + |
| 32 | + return $new; |
| 33 | + } |
| 34 | + |
| 35 | + public function multipliedBy( |
| 36 | + BigNumber|int|float|string $that, |
| 37 | + ): static { |
| 38 | + $new = clone $this; |
| 39 | + $new->value = $new->value->multipliedBy($that); |
| 40 | + |
| 41 | + return $new; |
| 42 | + } |
| 43 | + |
| 44 | + public function dividedBy( |
| 45 | + BigNumber|int|float|string|self $that, |
| 46 | + ?int $scale = null, |
| 47 | + RoundingMode $roundingMode = RoundingMode::UNNECESSARY |
| 48 | + ): static { |
| 49 | + $new = clone $this; |
| 50 | + $new->value = $new->value->dividedBy($that, $scale, $roundingMode); |
| 51 | + |
| 52 | + return $new; |
| 53 | + } |
| 54 | + |
| 55 | + private function preprocessThat( |
| 56 | + BigNumber|int|float|string|self $that, |
| 57 | + ?int $scale = null, |
| 58 | + RoundingMode $roundingMode = RoundingMode::UNNECESSARY, |
| 59 | + ): BigDecimal { |
| 60 | + if ($that instanceof self) { |
| 61 | + return $that->convertTo($this->unit, $scale, $roundingMode)->value; |
| 62 | + } |
| 63 | + |
| 64 | + return BigDecimal::of($that); |
| 65 | + } |
| 66 | +} |
0 commit comments