1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace MichaelRubel\Couponables\Traits\Concerns; |
6
|
|
|
|
7
|
|
|
use MichaelRubel\Couponables\Exceptions\InvalidCouponTypeException; |
8
|
|
|
use MichaelRubel\Couponables\Exceptions\InvalidCouponValueException; |
9
|
|
|
|
10
|
|
|
trait CalculatesCosts |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Calculate the output value based on the coupon type. |
14
|
|
|
* |
15
|
|
|
* @param float $using |
16
|
|
|
* |
17
|
|
|
* @return float |
18
|
|
|
* @throws InvalidCouponTypeException |
19
|
|
|
* @throws InvalidCouponValueException |
20
|
|
|
*/ |
21
|
10 |
|
public function calc(float $using): float |
22
|
|
|
{ |
23
|
10 |
|
$discount = (float) $this->{static::$bindable->getValueColumn()}; |
24
|
|
|
|
25
|
10 |
|
if ($this->lessOrEqualsZero($discount)) { |
26
|
2 |
|
throw new InvalidCouponValueException; |
27
|
|
|
} |
28
|
|
|
|
29
|
8 |
|
$result = match ($this->{static::$bindable->getTypeColumn()}) { |
30
|
8 |
|
static::TYPE_SUBTRACTION => $this->subtract($using, $discount), |
|
|
|
|
31
|
7 |
|
static::TYPE_PERCENTAGE => $this->percentage($using, $discount), |
|
|
|
|
32
|
2 |
|
static::TYPE_FIXED => $this->fixedPrice($discount), |
|
|
|
|
33
|
1 |
|
default => throw new InvalidCouponTypeException, |
34
|
|
|
}; |
35
|
|
|
|
36
|
7 |
|
return max( |
37
|
7 |
|
round($result, config('couponables.round') ?? 2), |
38
|
7 |
|
config('couponables.max') ?? 0 |
39
|
|
|
); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param float $value |
44
|
|
|
* @return bool |
45
|
|
|
*/ |
46
|
10 |
|
private function lessOrEqualsZero(float $value): bool |
47
|
|
|
{ |
48
|
10 |
|
return $value <= 0; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Apply the "Subtraction" calculation strategy. |
53
|
|
|
* |
54
|
|
|
* @param float $cost |
55
|
|
|
* @param float $discount |
56
|
|
|
* |
57
|
|
|
* @return float |
58
|
|
|
*/ |
59
|
1 |
|
private function subtract(float $cost, float $discount): float |
60
|
|
|
{ |
61
|
1 |
|
return $cost - $discount; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Apply the "Percentage" calculation strategy. |
66
|
|
|
* |
67
|
|
|
* @param float $value |
68
|
|
|
* @param float $discount |
69
|
|
|
* |
70
|
|
|
* @return float |
71
|
|
|
*/ |
72
|
5 |
|
private function percentage(float $value, float $discount): float |
73
|
|
|
{ |
74
|
5 |
|
return (1.0 - ($discount / 100)) * $value; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Apply the "Fixed Price" calculation strategy. |
79
|
|
|
* |
80
|
|
|
* @param float $discount |
81
|
|
|
* @return float |
82
|
|
|
*/ |
83
|
1 |
|
private function fixedPrice(float $discount): float |
84
|
|
|
{ |
85
|
1 |
|
return $discount; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|