Issues (41)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/ShoppingCart.php (6 issues)

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
/*
4
 * Cart module for Yii2
5
 *
6
 * @link      https://github.com/hiqdev/yii2-cart
7
 * @package   yii2-cart
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2015-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hiqdev\yii2\cart;
13
14
use hiqdev\yii2\cart\behaviors\EnsureDeleteRelatedPosition;
15
use Yii;
16
use yii\base\Event;
17
use yz\shoppingcart\CartActionEvent;
18
19
/**
20
 * Class ShoppingCart.
21
 * @property CartPositionInterface[] $positions
22
 */
23
class ShoppingCart extends \yz\shoppingcart\ShoppingCart
24
{
25
    /**
26
     * @var CartPositionInterface[]
27
     * TODO make local AbstractCartPosition
28
     */
29
    protected $_positions = [];
30
31
    /**
32
     * The cart module.
33
     */
34
    public $module;
35
36
    public function behaviors()
37
    {
38
        return [
39 1
            [
40
                'class' => EnsureDeleteRelatedPosition::class,
41 1
            ]
42
        ];
43
    }
44 1
45
    /**
46 1
     * @return integer
47 1
     */
48 1
    public function getCount(): int
49
    {
50
        $count = 0;
51 1
        foreach ($this->_positions as $position) {
52
            if (!$position->hasParent()) {
53
                $count += 1;
54 2
            }
55
        }
56 2
57
        return $count;
58
    }
59 2
60
    public function findRelatedFor(CartPositionInterface $parent): ?CartPositionInterface
61 2
    {
62
        foreach ($this->_positions as $position) {
63
            if ($position->hasParent() && $position->parent_id === $parent->getId()) {
0 ignored issues
show
Accessing parent_id on the interface hiqdev\yii2\cart\CartPositionInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
64 1
                return $position;
65
            }
66 1
        }
67
68
        return null;
69 1
    }
70
71 1
    /**
72
     * @return CartPositionInterface[]
73
     */
74
    public function getRootPositions(): array
75
    {
76
        return array_filter($this->getPositions(), static function (CartPositionInterface $position): bool {
77
            return !$position->hasParent();
78
        });
79
    }
80
81
    public function getQuantity()
82
    {
83
        $count = 0;
84
        foreach ($this->_positions as $position) {
85
            $count += $position->getQuantity();
86
        }
87
88
        return $count;
89
    }
90
91
    public function getSubtotal()
92
    {
93
        return $this->getCost(false);
94
    }
95
96
    public function getTotal()
97
    {
98
        return $this->getCost(true);
99
    }
100
101
    public function getDiscount()
102
    {
103
        return $this->getTotal() - $this->getSubtotal();
104
    }
105
106
    public function formatCurrency($sum, $currency = null)
107
    {
108
        return $sum !== null ? Yii::$app->formatter->format($sum, ['currency', $currency ?? $this->getCurrency()]) : '--';
109
    }
110
111
    /**
112
     * Sets cart from serialized string
113
     * @param string $serialized
114
     */
115
    public function setSerialized($serialized)
116
    {
117
        try {
118
            parent::setSerialized($serialized);
119
        } catch (\Exception $e) {
120
            Yii::error('Failed to unserlialize cart: ' . $e->getMessage(), __METHOD__);
121
            $this->_positions = [];
122
            $this->saveToSession();
123
        }
124
    }
125
126
    /**
127
     * Checks whether any of cart positions has error in `id` attribute.
128
     * @return boolean
129
     */
130
    public function hasErrors()
131
    {
132
        foreach ($this->_positions as $position) {
133
            if ($position->hasErrors('id')) {
0 ignored issues
show
The method hasErrors() does not seem to exist on object<hiqdev\yii2\cart\CartPositionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
134
                return true;
135
            }
136
        }
137
138
        return false;
139
    }
140
141
    /**
142
     * @param CartPositionInterface[] $positions
143
     */
144
    public function putPositions($positions)
145
    {
146
        foreach ($positions as $position) {
147
            if (isset($this->_positions[$position->getId()])) {
148
                if ($position instanceof DontIncrementQuantityWhenAlreadyInCart) {
149
                    continue;
150
                }
151
                $existingPosition = $this->_positions[$position->getId()];
152
                $existingPosition->setQuantity($existingPosition->getQuantity() + 1);
153
            } else {
154
                if ($position->getQuantity() <= 0) {
155
                    $position->setQuantity(1);
156
                }
157
                $this->_positions[$position->getId()] = $position;
158
                $this->trigger(self::EVENT_POSITION_PUT, new CartActionEvent([
159
                    'action' => CartActionEvent::ACTION_POSITION_PUT,
160
                    'position' => $position,
161
                ]));
162
            }
163
        }
164
165
        $this->trigger(self::EVENT_CART_CHANGE, new CartActionEvent([
166
            'action' => CartActionEvent::ACTION_POSITION_PUT,
167
        ]));
168
        if ($this->storeInSession)
169
            $this->saveToSession();
170
    }
171
172
173
    /**
174
     * This cart does not support multi-currency checkout.
175
     *
176
     * @return string|null When the cart is empty, returns {@see getDefaultCurrency()}.
177
     * When cart has at least one position, returns the first position currency.
178
     * Note, that the position currency may be undefined – in this case, `null` will be returned.
179
     */
180
    public function getCurrency(): ?string
181
    {
182
        if (empty($this->_positions)) {
183
            return $this->getDefaultCurrency();
184
        }
185
186
        return reset($this->_positions)->currency;
187
    }
188
189
    /**
190
     * Returns a default cart currency
191
     *
192
     * @return string
193
     */
194
    public function getDefaultCurrency(): string
195
    {
196
        return Yii::$app->params['currency'];
197
    }
198
199
    /**
200
     * @return array
201
     */
202
    public function getAdditionalLinks(): array
203
    {
204
        $links = [];
205
        $positions = $this->_positions;
206
        if (empty($positions)) {
207
            return $links;
208
        }
209
210
        foreach ($positions as $position) {
211
            $additionalLinks = $position->getAdditionalLinks();
212
            if (!empty($additionalLinks)) {
213
                foreach ($additionalLinks as $link) {
214
                    [$url, $label] = $link;
0 ignored issues
show
The variable $url does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
The variable $label does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
215
                    if ($url && $label && !isset($links[$url])) {
216
                        $links[$url] = $label;
217
                    }
218
                }
219
            }
220
        }
221
222
        return $links;
223
    }
224
225
    /**
226
     * @var CartActionEvent[]|null
227
     */
228
    private $_accumulatedEvents;
229
    public function trigger($name, Event $event = null)
230
    {
231
        if (is_array($this->_accumulatedEvents)) {
232
            \Yii::info("Shopping cart accumulates event $name");
233
            $this->_accumulatedEvents[] = [$name, $event];
234
        } else {
235
            parent::trigger($name, $event);
236
        }
237
    }
238
239
    /**
240
     * Runs $closure and accumulates all events occurred during $closure run.
241
     * Events get released immediately after a success $closure run.
242
     *
243
     * The method can be used to prevent useless calculations that happen after
244
     * bunch of similar updates on a cart.
245
     *
246
     * @param \Closure $closure
247
     */
248
    public function accumulateEvents(\Closure $closure): void
249
    {
250
        $this->_accumulatedEvents = [];
251
        try {
252
            $closure();
253
            $events = $this->_accumulatedEvents;
254
            $this->_accumulatedEvents = null;
255
            foreach ($events as [$name, $event]) {
256
                \Yii::info("Releases event $name");
0 ignored issues
show
The variable $name does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
257
                $this->trigger($name, $event);
0 ignored issues
show
The variable $event does not exist. Did you mean $events?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
258
            }
259
        } finally {
260
            $this->_accumulatedEvents = null;
261
        }
262
    }
263
}
264