/
ProductDiscount.php
126 lines (107 loc) · 2.92 KB
/
ProductDiscount.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<?php
/**
* Pimcore
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Commercial License (PCL)
* Full copyright and license information is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PCL
*/
namespace Pimcore\Bundle\EcommerceFrameworkBundle\PricingManager\Action;
use Pimcore\Bundle\EcommerceFrameworkBundle\PricingManager\ActionInterface;
use Pimcore\Bundle\EcommerceFrameworkBundle\PricingManager\EnvironmentInterface;
use Pimcore\Bundle\EcommerceFrameworkBundle\Type\Decimal;
// TODO use Decimal for amounts?
class ProductDiscount implements ProductDiscountInterface
{
/**
* @var float
*/
protected $amount = 0;
/**
* @var float
*/
protected $percent = 0;
/**
* @param EnvironmentInterface $environment
*
* @return ActionInterface
*/
public function executeOnProduct(EnvironmentInterface $environment)
{
$priceinfo = $environment->getPriceInfo();
$amount = Decimal::create($this->amount);
// TODO use discount()?
if ($amount->equals(Decimal::create(0))) {
$amount = $priceinfo->getAmount()->mul($this->getPercent() / 100);
}
$amount = $priceinfo->getAmount()->sub($amount);
$priceinfo->setAmount($amount->isPositive() ? $amount : Decimal::zero());
return $this;
}
/**
* @return string
*/
public function toJSON()
{
return json_encode([
'type' => 'ProductDiscount',
'amount' => $this->getAmount(),
'percent' => $this->getPercent(),
]);
}
/**
* @param string $string
*
* @return ActionInterface
*/
public function fromJSON($string)
{
$json = json_decode($string);
if ($json->amount) {
if($json->amount < 0) {
throw new \Exception('Only positive numbers and 0 are valid values for absolute discounts');
}
$this->setAmount($json->amount);
}
if ($json->percent) {
if($json->percent < 0) {
throw new \Exception('Only positive numbers and 0 are valid values for % discounts');
}
$this->setPercent($json->percent);
}
return $this;
}
/**
* @param float $amount
*/
public function setAmount($amount)
{
$this->amount = $amount;
}
/**
* @return float
*/
public function getAmount()
{
return $this->amount;
}
/**
* @param float $percent
*/
public function setPercent($percent)
{
$this->percent = $percent;
}
/**
* @return float
*/
public function getPercent()
{
return $this->percent;
}
}