Cart::getItems()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 2
nc 2
nop 1
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));
0 ignored issues
show
Bug introduced by
It seems like $this->storageClass can also be of type object<yii2mod\cart\storage\StorageInterface>; however, yii\BaseYii::createObject() does only seem to accept callable, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
48
        $this->items = $this->storage->load($this);
0 ignored issues
show
Bug introduced by
The property storage does not seem to exist. Did you mean storageClass?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
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);
0 ignored issues
show
Bug introduced by
The property storage does not seem to exist. Did you mean storageClass?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
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);
0 ignored issues
show
Bug introduced by
The property storage does not seem to exist. Did you mean storageClass?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
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');
0 ignored issues
show
Deprecated Code introduced by
The class yii\base\InvalidParamException has been deprecated with message: since 2.0.14. Use [[InvalidArgumentException]] instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
138
        }
139
140
        unset($this->items[$uniqueId]);
141
142
        $save && $this->storage->save($this);
0 ignored issues
show
Bug introduced by
The property storage does not seem to exist. Did you mean storageClass?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
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_a($item, $itemType);
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