Completed
Push — master ( e10c5a...89d86d )
by Igor
12s
created

Cart.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace yii2mod\cart;
4
5
use Yii;
6
use yii\base\Component;
7
use yii\base\InvalidParamException;
8
use yii2mod\cart\models\CartItemInterface;
9
use yii2mod\cart\storage\StorageInterface;
10
11
/**
12
 * Class Cart provides basic cart functionality (adding, removing, clearing, listing items). You can extend this class and
13
 * override it in the application configuration to extend/customize the functionality
14
 *
15
 * @package yii2mod\cart
16
 */
17
class Cart extends Component
18
{
19
    /**
20
     * @var string CartItemInterface class name
21
     */
22
    const ITEM_PRODUCT = '\yii2mod\cart\models\CartItemInterface';
23
24
    /**
25
     * Override this to provide custom (e.g. database) storage for cart data
26
     *
27
     * @var string|\yii2mod\cart\storage\StorageInterface
28
     */
29
    public $storageClass = '\yii2mod\cart\storage\SessionStorage';
30
31
    /**
32
     * @var array cart items
33
     */
34
    protected $items;
35
36
    /**
37
     * @var StorageInterface
38
     */
39
    private $_storage;
40
41
    /**
42
     * @inheritdoc
43
     */
44
    public function init()
45
    {
46
        $this->clear(false);
47
        $this->setStorage(Yii::createObject($this->storageClass));
48
        $this->items = $this->storage->load($this);
49
    }
50
51
    /**
52
     * Assigns cart to logged in user
53
     *
54
     * @param string
55
     * @param string
56
     */
57
    public function reassign($sessionId, $userId)
58
    {
59
        if (get_class($this->getStorage()) === 'yii2mod\cart\storage\DatabaseStorage') {
60
            if (!empty($this->items)) {
61
                $storage = $this->getStorage();
62
                $storage->reassign($sessionId, $userId);
63
                self::init();
64
            }
65
        }
66
    }
67
68
    /**
69
     * Delete all items from the cart
70
     *
71
     * @param bool $save
72
     *
73
     * @return $this
74
     */
75
    public function clear($save = true): self
76
    {
77
        $this->items = [];
78
        $save && $this->storage->save($this);
79
80
        return $this;
81
    }
82
83
    /**
84
     * @return StorageInterface
85
     */
86
    public function getStorage(): StorageInterface
87
    {
88
        return $this->_storage;
89
    }
90
91
    /**
92
     * @param mixed $storage
93
     */
94
    public function setStorage($storage)
95
    {
96
        $this->_storage = $storage;
97
    }
98
99
    /**
100
     * Add an item to the cart
101
     *
102
     * @param models\CartItemInterface $element
103
     * @param bool $save
104
     *
105
     * @return $this
106
     */
107
    public function add(CartItemInterface $element, $save = true): self
108
    {
109
        $this->addItem($element);
110
        $save && $this->storage->save($this);
111
112
        return $this;
113
    }
114
115
    /**
116
     * @param \yii2mod\cart\models\CartItemInterface $item
117
     */
118
    protected function addItem(CartItemInterface $item)
119
    {
120
        $uniqueId = $item->getUniqueId();
121
        $this->items[$uniqueId] = $item;
122
    }
123
124
    /**
125
     * Removes an item from the cart
126
     *
127
     * @param string $uniqueId
128
     * @param bool $save
129
     *
130
     * @throws \yii\base\InvalidParamException
131
     *
132
     * @return $this
133
     */
134
    public function remove($uniqueId, $save = true): self
135
    {
136
        if (!isset($this->items[$uniqueId])) {
137
            throw new InvalidParamException('Item not found');
138
        }
139
140
        unset($this->items[$uniqueId]);
141
142
        $save && $this->storage->save($this);
143
144
        return $this;
145
    }
146
147
    /**
148
     * @param string $itemType If specified, only items of that type will be counted
149
     *
150
     * @return int
151
     */
152
    public function getCount($itemType = null): int
153
    {
154
        return count($this->getItems($itemType));
155
    }
156
157
    /**
158
     * Returns all items of a given type from the cart
159
     *
160
     * @param string $itemType One of self::ITEM_ constants
161
     *
162
     * @return CartItemInterface[]
163
     */
164
    public function getItems($itemType = null): array
165
    {
166
        $items = $this->items;
167
168
        if (!is_null($itemType)) {
169
            $items = array_filter(
170
                $items,
171
                function ($item) use ($itemType) {
172
                    /* @var $item CartItemInterface */
173
                    return is_subclass_of($item, $itemType);
0 ignored issues
show
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if $itemType can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
174
                }
175
            );
176
        }
177
178
        return $items;
179
    }
180
181
    /**
182
     * Finds all items of type $itemType, sums the values of $attribute of all models and returns the sum.
183
     *
184
     * @param string $attribute
185
     * @param string|null $itemType
186
     *
187
     * @return int
188
     */
189
    public function getAttributeTotal($attribute, $itemType = null): int
190
    {
191
        $sum = 0;
192
        foreach ($this->getItems($itemType) as $model) {
193
            $sum += $model->{$attribute};
194
        }
195
196
        return $sum;
197
    }
198
}
199