forked from omnilight/yii2-shopping-cart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CartPositionTrait.php
46 lines (40 loc) · 1.17 KB
/
CartPositionTrait.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
<?php
namespace yz\shoppingcart;
use yii\base\Component;
use yii\base\Object;
/**
* Trait CartPositionTrait
* @property int $quantity Returns quantity of cart position
* @property int $cost Returns cost of cart position. Default value is 'price * quantity'
* @package yz\shoppingcart
*/
trait CartPositionTrait
{
protected $_quantity;
public function getQuantity()
{
return $this->_quantity;
}
public function setQuantity($quantity)
{
$this->_quantity = $quantity;
}
/**
* Default implementation for getCost function. Cost is calculated as price * quantity
* @param bool $withDiscount
* @return int
*/
public function getCost($withDiscount = true)
{
/** @var Component|CartPositionInterface|self $this */
$cost = $this->getQuantity() * $this->getPrice();
$costEvent = new CostCalculationEvent([
'baseCost' => $cost,
]);
if ($this instanceof Component)
$this->trigger(CartPositionInterface::EVENT_COST_CALCULATION, $costEvent);
if ($withDiscount)
$cost = max(0, $cost - $costEvent->discountValue);
return $cost;
}
}