Completed
Pull Request — 2.0 (#507)
by Roman
19:52 queued 20s
created

ShoppingCart_Controller   D

Complexity

Total Complexity 52

Size/Duplication

Total Lines 282
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 18

Test Coverage

Coverage 76.42%

Importance

Changes 5
Bugs 1 Features 2
Metric Value
wmc 52
c 5
b 1
f 2
lcom 1
cbo 18
dl 0
loc 282
ccs 94
cts 123
cp 0.7642
rs 4.3439

17 Methods

Rating   Name   Duplication   Size   Complexity  
A add_item_link() 0 4 1
A remove_item_link() 0 4 1
A remove_all_item_link() 0 4 1
A set_quantity_item_link() 0 4 1
B build_url() 0 14 5
A params_to_get_string() 0 8 2
A direct() 0 13 4
A init() 0 5 1
D buyableFromRequest() 0 38 10
A add() 0 14 4
A remove() 0 10 3
A removeall() 0 10 3
A setquantity() 0 12 3
A clear() 0 7 2
A index() 0 10 3
A debug() 0 14 4
A updateLocale() 0 7 4

How to fix   Complexity   

Complex Class

Complex classes like ShoppingCart_Controller often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ShoppingCart_Controller, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * Encapsulated manipulation of the current order using a singleton pattern.
5
 *
6
 * Ensures that an order is only started (persisted to DB) when necessary,
7
 * and all future changes are on the same order, until the order has is placed.
8
 * The requirement for starting an order is to adding an item to the cart.
9
 *
10
 * @package shop
11
 */
12
class ShoppingCart extends Object
0 ignored issues
show
Complexity introduced by
This class has a complexity of 50 which exceeds the configured maximum of 50.

The class complexity is the sum of the complexity of all methods. A very high value is usually an indication that your class does not follow the single reponsibility principle and does more than one job.

Some resources for further reading:

You can also find more detailed suggestions for refactoring in the “Code” section of your repository.

Loading history...
13
{
14
    private static $cartid_session_name = 'shoppingcartid';
15
16
    private        $order;
17
18
    private        $calculateonce       = false;
19
20
    private        $message;
21
22
    private        $type;
23
24
    /**
25
     * Access for only allowing access to one (singleton) ShoppingCart.
26
     *
27
     * @return ShoppingCart
28
     */
29 92
    public static function singleton()
30
    {
31 92
        return Injector::inst()->get('ShoppingCart');
32
    }
33
34
    /**
35
     * Shortened alias for ShoppingCart::singleton()->current()
36
     *
37
     * @return Order
38
     */
39 17
    public static function curr()
40
    {
41 17
        return self::singleton()->current();
42
    }
43
44
    /**
45
     * Get the current order, or return null if it doesn't exist.
46
     *
47
     * @return Order
48
     */
49 92
    public function current()
50
    {
51
        //find order by id saved to session (allows logging out and retaining cart contents)
52 92
        if (!$this->order && $sessionid = Session::get(self::config()->cartid_session_name)) {
53
            $this->order = Order::get()->filter(
54
                array(
55
                    "Status" => "Cart",
56
                    "ID"     => $sessionid,
57
                )
58
            )->first();
59
        }
60 92
        if (!$this->calculateonce && $this->order) {
61 9
            $this->order->calculate();
62 9
            $this->calculateonce = true;
63 9
        }
64
65 92
        return $this->order ? $this->order : false;
66
    }
67
68
    /**
69
     * Set the current cart
70
     *
71
     * @param Order
72
     *
73
     * @return ShoppingCart
74
     */
75 20
    public function setCurrent(Order $cart)
76 19
    {
77 7
        if (!$cart->IsCart()) {
78
            trigger_error("Passed Order object is not cart status", E_ERROR);
79
        }
80 7
        $this->order = $cart;
81 7
        Session::set(self::config()->cartid_session_name, $cart->ID);
82
83 7
        return $this;
84
    }
85
86
    /**
87
     * Helper that only allows orders to be started internally.
88
     *
89
     * @return Order
90
     */
91 19
    protected function findOrMake()
92
    {
93 19
        if ($this->current()) {
94 19
            return $this->current();
95
        }
96 13
        $this->order = Order::create();
97 13
        if (Member::config()->login_joins_cart && Member::currentUserID()) {
98 4
            $this->order->MemberID = Member::currentUserID();
99 4
        }
100 13
        $this->order->write();
101 13
        $this->order->extend('onStartOrder');
102 13
        Session::set(self::config()->cartid_session_name, $this->order->ID);
103
104 13
        return $this->order;
105
    }
106
107
    /**
108
     * Adds an item to the cart
109
     *
110
     * @param Buyable $buyable
111
     * @param number  $quantity
112
     * @param unknown $filter
113
     *
114
     * @return boolean|OrderItem false or the new/existing item
115
     */
116 18
    public function add(Buyable $buyable, $quantity = 1, $filter = array())
117
    {
118 18
        $order = $this->findOrMake();
119 18
        $order->extend("beforeAdd", $buyable, $quantity, $filter);
120 18
        if (!$buyable) {
121
122
            return $this->error(_t("ShoppingCart.ProductNotFound", "Product not found."));
123
        }
124 18
        $item = $this->findOrMakeItem($buyable, $filter);
125 18
        if (!$item) {
126
127 1
            return false;
128
        }
129 18
        if (!$item->_brandnew) {
0 ignored issues
show
Documentation introduced by
The property _brandnew does not exist on object<OrderItem>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
130 4
            $item->Quantity += $quantity;
0 ignored issues
show
Documentation introduced by
The property Quantity does not exist on object<OrderItem>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
131 4
        } else {
132 18
            $item->Quantity = $quantity;
0 ignored issues
show
Documentation introduced by
The property Quantity does not exist on object<OrderItem>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
133
        }
134 18
        $item->write();
135 18
        $order->extend("afterAdd", $item, $buyable, $quantity, $filter);
136 18
        $this->message(_t("ShoppingCart.ItemAdded", "Item has been added successfully."));
137
138 18
        return $item;
139
    }
140
141
    /**
142
     * Remove an item from the cart.
143
     *
144
     * @param     id        or Buyable $buyable
145
     * @param     $item
146
     * @param int $quantity - number of items to remove, or leave null for all items (default)
147
     *
148
     * @return boolean success/failure
149
     */
150 4
    public function remove(Buyable $buyable, $quantity = null, $filter = array())
151
    {
152 4
        $order = $this->current();
153
154 4
        if (!$order) {
155
            return $this->error(_t("ShoppingCart.NoOrder", "No current order."));
156
        }
157
158 4
        $order->extend("beforeRemove", $buyable, $quantity, $filter);
159
160 4
        $item = $this->get($buyable, $filter);
161
162 4
        if (!$item) {
163 1
            return false;
164
        }
165
166
        //if $quantity will become 0, then remove all
167 4
        if (!$quantity || ($item->Quantity - $quantity) <= 0) {
168 4
            $item->delete();
169 4
            $item->destroy();
170 4
        } else {
171 1
            $item->Quantity -= $quantity;
172 1
            $item->write();
173
        }
174 4
        $order->extend("afterRemove", $item, $buyable, $quantity, $filter);
175 4
        $this->message(_t("ShoppingCart.ItemRemoved", "Item has been successfully removed."));
176
177 4
        return true;
178
    }
179
180
    /**
181
     * Sets the quantity of an item in the cart.
182
     * Will automatically add or remove item, if necessary.
183
     *
184
     * @param     id or Buyable $buyable
185
     * @param     $item
186
     * @param int $quantity
187
     *
188
     * @return boolean|OrderItem false or the new/existing item
189
     */
190 3
    public function setQuantity(Buyable $buyable, $quantity = 1, $filter = array())
191
    {
192 3
        if ($quantity <= 0) {
193
            return $this->remove($buyable, $quantity, $filter);
194
        }
195 3
        $order = $this->findOrMake();
196 3
        $item = $this->findOrMakeItem($buyable, $filter);
197 3
        if (!$item) {
198
199
            return false;
200
        }
201 3
        $order->extend("beforeSetQuantity", $buyable, $quantity, $filter);
202 3
        $item->Quantity = $quantity;
0 ignored issues
show
Documentation introduced by
The property Quantity does not exist on object<OrderItem>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
203 3
        $item->write();
204 3
        $order->extend("afterSetQuantity", $item, $buyable, $quantity, $filter);
205 3
        $this->message(_t("ShoppingCart.QuantitySet", "Quantity has been set."));
206
207 3
        return $item;
208
    }
209
210
    /**
211
     * Finds or makes an order item for a given product + filter.
212
     *
213
     * @param        id or Buyable $buyable
214
     * @param string $filter
215
     *
216
     * @return OrderItem the found or created item
217
     */
218 19
    private function findOrMakeItem(Buyable $buyable, $filter = array())
219
    {
220 19
        $order = $this->findOrMake();
221
222 19
        if (!$buyable || !$order) {
223 3
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by ShoppingCart::findOrMakeItem of type OrderItem.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
224
        }
225
226 19
        $item = $this->get($buyable, $filter);
0 ignored issues
show
Bug introduced by
It seems like $filter defined by parameter $filter on line 218 can also be of type string; however, ShoppingCart::get() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug Compatibility introduced by
The expression $this->get($buyable, $filter); of type the adds the type the to the return on line 252 which is incompatible with the return type documented by ShoppingCart::findOrMakeItem of type OrderItem.
Loading history...
227
228 19
        if (!$item) {
229 19
            $member = Member::currentUser();
230
231 19
            if (!$buyable->canPurchase($member)) {
0 ignored issues
show
Bug introduced by
It seems like $member defined by \Member::currentUser() on line 229 can also be of type object<DataObject>; however, Buyable::canPurchase() does only seem to accept object<Member>|null, 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...
232 1
                return $this->error(
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->error(_t('...18n_singular_name()))); (boolean) is incompatible with the return type documented by ShoppingCart::findOrMakeItem of type OrderItem.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
233 1
                    _t(
234 1
                        'ShoppingCart.CannotPurchase',
235 1
                        'This {Title} cannot be purchased.',
236 1
                        '',
237 1
                        array('Title' => $buyable->i18n_singular_name())
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Buyable as the method i18n_singular_name() does only exist in the following implementations of said interface: CustomProduct, ProductVariation.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
Documentation introduced by
array('Title' => $buyable->i18n_singular_name()) is of type array<string,?,{"Title":"?"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
238 1
                    )
239 1
                );
240
                //TODO: produce a more specific message
241
            }
242
243 19
            $item = $buyable->createItem(1, $filter);
0 ignored issues
show
Bug introduced by
It seems like $filter defined by parameter $filter on line 218 can also be of type string; however, Buyable::createItem() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
244 19
            $item->OrderID = $order->ID;
0 ignored issues
show
Documentation introduced by
The property OrderID does not exist on object<OrderItem>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
245 19
            $item->write();
246
247 19
            $order->Items()->add($item);
0 ignored issues
show
Documentation Bug introduced by
The method Items does not exist on object<Order>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
248
249 19
            $item->_brandnew = true; // flag as being new
0 ignored issues
show
Documentation introduced by
The property _brandnew does not exist on object<OrderItem>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
250 19
        }
251
252 19
        return $item;
253
    }
254
255
    /**
256
     * Finds an existing order item.
257
     *
258
     * @param Buyable $buyable
259
     * @param string  $filter
0 ignored issues
show
Documentation introduced by
There is no parameter named $filter. Did you maybe mean $customfilter?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
260
     *
261
     * @return the item requested, or false
262
     */
263 22
    public function get(Buyable $buyable, $customfilter = array())
264 3
    {
265 22
        $order = $this->current();
266 22
        if (!$buyable || !$order) {
267 5
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by ShoppingCart::get of type the.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
268
        }
269
        $filter = array(
270 21
            'OrderID' => $order->ID,
271 21
        );
272 21
        $itemclass = Config::inst()->get(get_class($buyable), 'order_item');
273 21
        $relationship = Config::inst()->get($itemclass, 'buyable_relationship');
274 21
        $filter[$relationship . "ID"] = $buyable->ID;
0 ignored issues
show
Bug introduced by
Accessing ID on the interface Buyable 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...
275 21
        $required = array('Order', $relationship);
276 21
        if (is_array($itemclass::config()->required_fields)) {
277 21
            $required = array_merge($required, $itemclass::config()->required_fields);
278 21
        }
279 21
        $query = new MatchObjectFilter($itemclass, array_merge($customfilter, $filter), $required);
280 21
        $item = $itemclass::get()->where($query->getFilter())->first();
281 21
        if (!$item) {
282 21
            return $this->error(_t("ShoppingCart.ItemNotFound", "Item not found."));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->error(_t('...', 'Item not found.')); (boolean) is incompatible with the return type documented by ShoppingCart::get of type the.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
283
        }
284
285 12
        return $item;
286
    }
287
288
    /**
289
     * Store old cart id in session order history
290
     * @param int|null $requestedOrderId optional parameter that denotes the order that was requested
291
     */
292 1
    public function archiveorderid($requestedOrderId = null)
293
    {
294
        $sessionId = Session::get(self::config()->cartid_session_name);
295 1
        $order = Order::get()
296
            ->filter("Status:not", "Cart")
297
            ->byId($sessionId);
298
        if ($order && !$order->IsCart()) {
299
            OrderManipulation::add_session_order($order);
0 ignored issues
show
Compatibility introduced by
$order of type object<DataObject> is not a sub-type of object<Order>. It seems like you assume a child class of the class DataObject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
300
        }
301
        // in case there was no order requested
302
        // OR there was an order requested AND it's the same one as currently in the session,
303
        // then clear the cart. This check is here to prevent clearing of the cart if the user just
304
        // wants to view an old order (via AccountPage).
305
        if (!$requestedOrderId || ($sessionId == $requestedOrderId)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $requestedOrderId of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
306
            $this->clear();
307
        }
308
    }
309
310
    /**
311
     * Empty / abandon the entire cart.
312
     *
313
     * @return bool - true if successful, false if no cart found
314
     */
315 12
    public function clear()
316
    {
317 10
        Session::clear(self::config()->cartid_session_name);
318 10
        $order = $this->current();
319 10
        $this->order = null;
320 10
        if (!$order) {
321 4
            return $this->error(_t("ShoppingCart.NoCartFound", "No cart found."));
322
        }
323 9
        $order->write();
324 9
        $this->message(_t("ShoppingCart.Cleared", "Cart was successfully cleared."));
325
326 9
        return true;
327 9
    }
328
329
    /**
330
     * Store a new error.
331
     */
332 22
    protected function error($message)
333
    {
334 22
        $this->message($message, "bad");
335
336 22
        return false;
337
    }
338
339
    /**
340
     * Store a message to be fed back to user.
341
     *
342
     * @param string $message
343
     * @param string $type - good, bad, warning
344
     */
345 23
    protected function message($message, $type = "good")
346
    {
347 23
        $this->message = $message;
348 23
        $this->type = $type;
349 23
    }
350
351
    public function getMessage()
352
    {
353
        return $this->message;
354
    }
355
356
    public function getMessageType()
357
    {
358
        return $this->type;
359
    }
360
361
    public function clearMessage()
362
    {
363
        $this->message = null;
364
    }
365
366
    //singleton protection
367
    public function __clone()
368
    {
369
        trigger_error('Clone is not allowed.', E_USER_ERROR);
370
    }
371
372
    public function __wakeup()
373
    {
374
        trigger_error('Unserializing is not allowed.', E_USER_ERROR);
375
    }
376
}
377
378
/**
379
 * Manipulate the cart via urls.
380
 */
381
class ShoppingCart_Controller extends Controller
0 ignored issues
show
Complexity introduced by
This class has a complexity of 52 which exceeds the configured maximum of 50.

The class complexity is the sum of the complexity of all methods. A very high value is usually an indication that your class does not follow the single reponsibility principle and does more than one job.

Some resources for further reading:

You can also find more detailed suggestions for refactoring in the “Code” section of your repository.

Loading history...
382
{
383
    private static $url_segment         = "shoppingcart";
384
385
    private static $direct_to_cart_page = false;
386
387
    protected      $cart;
388
389
    private static $url_handlers        = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
390
        '$Action/$Buyable/$ID' => 'handleAction',
391
    );
392
393
    private static $allowed_actions     = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
394
        'add',
395
        'additem',
396
        'remove',
397
        'removeitem',
398
        'removeall',
399
        'removeallitem',
400
        'setquantity',
401
        'setquantityitem',
402
        'clear',
403
        'debug',
404
    );
405
406 6
    public static function add_item_link(Buyable $buyable, $parameters = array())
407
    {
408 6
        return self::build_url("add", $buyable, $parameters);
409
    }
410
411 2
    public static function remove_item_link(Buyable $buyable, $parameters = array())
412
    {
413 2
        return self::build_url("remove", $buyable, $parameters);
414
    }
415
416 2
    public static function remove_all_item_link(Buyable $buyable, $parameters = array())
417
    {
418 2
        return self::build_url("removeall", $buyable, $parameters);
419
    }
420
421 3
    public static function set_quantity_item_link(Buyable $buyable, $parameters = array())
422
    {
423 3
        return self::build_url("setquantity", $buyable, $parameters);
424
    }
425
426
    /**
427
     * Helper for creating a url
428
     */
429 6
    protected static function build_url($action, $buyable, $params = array())
430
    {
431 6
        if (!$action || !$buyable) {
432
            return false;
433
        }
434 6
        if (SecurityToken::is_enabled() && !self::config()->disable_security_token) {
435 1
            $params[SecurityToken::inst()->getName()] = SecurityToken::inst()->getValue();
436 1
        }
437 6
        return self::config()->url_segment . '/' .
438 6
        $action . '/' .
439 6
        $buyable->class . "/" .
440 6
        $buyable->ID .
441 6
        self::params_to_get_string($params);
442
    }
443
444
    /**
445
     * Creates the appropriate string parameters for links from array
446
     *
447
     * Produces string such as: MyParam%3D11%26OtherParam%3D1
448
     *     ...which decodes to: MyParam=11&OtherParam=1
449
     *
450
     * you will need to decode the url with javascript before using it.
451
     */
452 6
    protected static function params_to_get_string($array)
453
    {
454 6
        if ($array & count($array > 0)) {
455 3
            array_walk($array, create_function('&$v,$k', '$v = $k."=".$v ;'));
456 3
            return "?" . implode("&", $array);
457
        }
458 6
        return "";
459
    }
460
461
    /**
462
     * This is used here and in VariationForm and AddProductForm
463
     *
464
     * @param bool|string $status
465
     *
466
     * @return bool
467
     */
468 4
    public static function direct($status = true)
469
    {
470 4
        if (Director::is_ajax()) {
471
            return $status;
472
        }
473 4
        if (self::config()->direct_to_cart_page && $cartlink = CartPage::find_link()) {
474
            Controller::curr()->redirect($cartlink);
475
            return;
476
        } else {
477 4
            Controller::curr()->redirectBack();
478 4
            return;
479
        }
480
    }
481
482 4
    public function init()
483
    {
484 4
        parent::init();
485 4
        $this->cart = ShoppingCart::singleton();
486 4
    }
487
488
    /**
489
     * @return Product|ProductVariation|Buyable
490
     */
491 4
    protected function buyableFromRequest()
0 ignored issues
show
Complexity introduced by
This operation has 480 execution paths which exceeds the configured maximum of 200.

A high number of execution paths generally suggests many nested conditional statements and make the code less readible. This can usually be fixed by splitting the method into several smaller methods.

You can also find more information in the “Code” section of your repository.

Loading history...
492
    {
493 4
        $request = $this->getRequest();
494
        if (
495 4
            SecurityToken::is_enabled() &&
496 4
            !self::config()->disable_security_token &&
497 1
            !SecurityToken::inst()->checkRequest($request)
498 4
        ) {
499 1
            return $this->httpError(
500 1
                400,
501 1
                _t("ShoppingCart.InvalidSecurityToken", "Invalid security token, possible CSRF attack.")
502 1
            );
503
        }
504 4
        $id = (int)$request->param('ID');
505 4
        if (empty($id)) {
506
            //TODO: store error message
507
            return null;
508
        }
509 4
        $buyableclass = "Product";
510 4
        if ($class = $request->param('Buyable')) {
511 4
            $buyableclass = Convert::raw2sql($class);
512 4
        }
513 4
        if (!ClassInfo::exists($buyableclass)) {
0 ignored issues
show
Bug introduced by
It seems like $buyableclass defined by \Convert::raw2sql($class) on line 511 can also be of type array; however, ClassInfo::exists() does only seem to accept string, 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...
514
            //TODO: store error message
515
            return null;
516
        }
517
        //ensure only live products are returned, if they are versioned
518 4
        $buyable = Object::has_extension($buyableclass, 'Versioned')
0 ignored issues
show
Bug introduced by
It seems like $buyableclass defined by \Convert::raw2sql($class) on line 511 can also be of type array; however, Object::has_extension() does only seem to accept string, 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...
519
            ?
520 4
            Versioned::get_by_stage($buyableclass, 'Live')->byID($id)
0 ignored issues
show
Bug introduced by
It seems like $buyableclass defined by \Convert::raw2sql($class) on line 511 can also be of type array; however, Versioned::get_by_stage() does only seem to accept string, 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...
521 4
            :
522 4
            DataObject::get($buyableclass)->byID($id);
0 ignored issues
show
Bug introduced by
It seems like $buyableclass defined by \Convert::raw2sql($class) on line 511 can also be of type array; however, DataObject::get() does only seem to accept string|null, 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...
523 4
        if (!$buyable || !($buyable instanceof Buyable)) {
524
            //TODO: store error message
525 1
            return null;
526
        }
527 4
        return $buyable;
528
    }
529
530
    /**
531
     * Action: add item to cart
532
     *
533
     * @param SS_HTTPRequest $request
534
     *
535
     * @return SS_HTTPResponse
536
     */
537 4
    public function add($request)
538
    {
539 4
        if ($product = $this->buyableFromRequest()) {
540 4
            $quantity = (int)$request->getVar('quantity');
541 4
            if (!$quantity) {
542 4
                $quantity = 1;
543 4
            }
544 4
            $this->cart->add($product, $quantity, $request->getVars());
545 4
        }
546
547 4
        $this->updateLocale($request);
548 4
        $this->extend('updateAddResponse', $request, $response, $product, $quantity);
549 4
        return $response ? $response : self::direct();
550
    }
551
552
    /**
553
     * Action: remove a certain number of items from the cart
554
     *
555
     * @param SS_HTTPRequest $request
556
     *
557
     * @return SS_HTTPResponse
558
     */
559 1
    public function remove($request)
560
    {
561 1
        if ($product = $this->buyableFromRequest()) {
562 1
            $this->cart->remove($product, $quantity = 1, $request->getVars());
563 1
        }
564
565 1
        $this->updateLocale($request);
566 1
        $this->extend('updateRemoveResponse', $request, $response, $product, $quantity);
567 1
        return $response ? $response : self::direct();
568
    }
569
570
    /**
571
     * Action: remove all of an item from the cart
572
     *
573
     * @param SS_HTTPRequest $request
574
     *
575
     * @return SS_HTTPResponse
576
     */
577 1
    public function removeall($request)
578
    {
579 1
        if ($product = $this->buyableFromRequest()) {
580 1
            $this->cart->remove($product, null, $request->getVars());
581 1
        }
582
583 1
        $this->updateLocale($request);
584 1
        $this->extend('updateRemoveAllResponse', $request, $response, $product);
585 1
        return $response ? $response : self::direct();
586
    }
587
588
    /**
589
     * Action: update the quantity of an item in the cart
590
     *
591
     * @param $request
592
     *
593
     * @return AjaxHTTPResponse|bool
594
     */
595 2
    public function setquantity($request)
596
    {
597 2
        $product = $this->buyableFromRequest();
598 2
        $quantity = (int)$request->getVar('quantity');
599 2
        if ($product) {
600 2
            $this->cart->setQuantity($product, $quantity, $request->getVars());
601 2
        }
602
603 2
        $this->updateLocale($request);
604 2
        $this->extend('updateSetQuantityResponse', $request, $response, $product, $quantity);
605 2
        return $response ? $response : self::direct();
606
    }
607
608
    /**
609
     * Action: clear the cart
610
     *
611
     * @param $request
612
     *
613
     * @return AjaxHTTPResponse|bool
614
     */
615
    public function clear($request)
616
    {
617
        $this->updateLocale($request);
618
        $this->cart->clear();
619
        $this->extend('updateClearResponse', $request, $response);
620
        return $response ? $response : self::direct();
621
    }
622
623
    /**
624
     * Handle index requests
625
     */
626
    public function index()
627
    {
628
        if ($cart = $this->Cart()) {
0 ignored issues
show
Documentation Bug introduced by
The method Cart does not exist on object<ShoppingCart_Controller>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
629
            $this->redirect($cart->CartLink);
630
            return;
631
        } elseif ($response = ErrorPage::response_for(404)) {
632
            return $response;
633
        }
634
        return $this->httpError(404, _t("ShoppingCart.NoCartInitialised", "no cart initialised"));
635
    }
636
637
    /**
638
     * Displays order info and cart contents.
639
     */
640
    public function debug()
641
    {
642
        if (Director::isDev() || Permission::check("ADMIN")) {
643
            //TODO: allow specifying a particular id to debug
644
            Requirements::css(SHOP_DIR . "/css/cartdebug.css");
645
            $order = ShoppingCart::curr();
646
            $content = ($order)
647
                ?
648
                Debug::text($order)
0 ignored issues
show
Documentation introduced by
$order is of type object<Order>, but the function expects a object<unknown_type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
649
                :
650
                "Cart has not been created yet. Add a product.";
651
            return array('Content' => $content);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array('Content' => $content); (array<string,unknown|string>) is incompatible with the return type of the parent method ViewableData::Debug of type ViewableData_Debugger.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
652
        }
653
    }
654
655 4
    protected function updateLocale($request)
656
    {
657 4
        $order = $this->cart->current();
658 4
        if ($request && $request->isAjax() && $order) {
659
            ShopTools::install_locale($order->Locale);
660
        }
661 4
    }
662
}
663