Completed
Push — master ( 6f1332...6fa227 )
by Scott
02:21
created

CartRepository::updateItem()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 2
eloc 7
nc 2
nop 2
1
<?php namespace Bedard\Shop\Repositories;
2
3
use Cookie;
4
use Session;
5
use Exception;
6
use Bedard\Shop\Models\Cart;
7
use Bedard\Shop\Models\CartItem;
8
use Bedard\Shop\Models\Inventory;
9
use Bedard\Shop\Models\CartSettings;
10
11
class CartRepository
12
{
13
    /**
14
     * @var string  Cart persistence key.
15
     */
16
    const CART_KEY = 'bedard_shop_cart';
17
18
    /**
19
     * @var \Bedard\Shop\Models\Cart
20
     */
21
    protected $cart = null;
22
23
    /**
24
     * Add an item to the curent cart.
25
     *
26
     * @param  int
27
     * @param  int
28
     * @return \Bedard\Shop\Models\Cart
29
     */
30
    public function addInventory($inventoryId, $quantity)
31
    {
32
        $inventory = Inventory::findOrFail($inventoryId);
33
34
        $cart = $this->getCart();
35
        $item = CartItem::firstOrCreate([
36
            'cart_id' => $cart->id,
37
            'inventory_id' => $inventory->id,
38
        ]);
39
40
        $item->quantity += $quantity;
41
        if ($item->quantity > $inventory->quantity) {
42
            $item->quantity = $inventory->quantity;
43
        }
44
45
        $item->save();
46
47
        $item->load([
48
            'inventory.optionValues.option',
49
            'inventory.product' => function ($product) {
50
                return $product->joinPrice()->with('thumbnails');
51
            },
52
        ]);
53
54
        return $item;
55
    }
56
57
    /**
58
     * Create a new cart.
59
     *
60
     * @return \Bedard\Shop\Models\Cart
61
     */
62
    public function create()
63
    {
64
        $this->cart = Cart::create();
65
66
        Session::put(self::CART_KEY, $this->cart->token);
67
        Cookie::queue(self::CART_KEY, $this->cart->token, CartSettings::getLifespan());
68
69
        return $this->cart;
70
    }
71
72
    /**
73
     * Delete an inventory from the cart.
74
     *
75
     * @param  int
76
     * @return \Bedard\Shop\Models\Cart
77
     */
78
    public function deleteItem($inventoryId)
79
    {
80
        $cart = $this->getCart();
81
82
        $item = $cart->items()->whereInventoryId($inventoryId)->first();
83
84
        if ($item) {
85
            return $item->delete();
86
        }
87
88
        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 Bedard\Shop\Repositories...tRepository::deleteItem of type Bedard\Shop\Models\Cart.

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...
89
    }
90
91
    /**
92
     * Determine if a cart exists.
93
     *
94
     * @return bool
95
     */
96
    public function exists()
97
    {
98
        $token = $this->getToken();
99
100
        return Cart::whereToken($token)->isOpen()->exists();
101
    }
102
103
    /**
104
     * Get the current cart, or create one if none exists.
105
     *
106
     * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
107
     * @return \Bedard\Shop\Models\Cart
108
     */
109
    public function getCart()
110
    {
111
        if ($this->cart !== null) {
112
            return $this->cart;
113
        }
114
115
        $token = $this->getToken();
116
117
        if (! $token) {
118
            return $this->create();
119
        }
120
121
        try {
122
            $this->cart = Cart::whereToken($token)
123
                ->isOpen()
124
                ->firstOrFail();
125
        } catch (Exception $e) {
126
            $this->cart = $this->create();
127
        }
128
129
        return $this->cart;
130
    }
131
132
    /**
133
     * Get the cart token.
134
     *
135
     * @return string
136
     */
137
    public function getToken()
138
    {
139
        $token = Session::get(self::CART_KEY);
140
        if (! $token && Cookie::has(self::CART_KEY)) {
141
            $token = Cookie::get(self::CART_KEY);
142
        }
143
144
        return $token;
145
    }
146
147
    /**
148
     * Load the related cart data.
149
     *
150
     * @return \Bedard\Shop\Models\Cart
151
     */
152
    public function loadCart()
153
    {
154
        $this->getCart()->load([
155
            'items.inventory.product' => function ($product) {
156
                $product->joinPrice()->with('thumbnails');
157
            },
158
            'items.inventory.optionValues.option',
159
        ]);
160
161
        return $this->cart;
162
    }
163
164
    /**
165
     * Set an item's quantity in the current cart.
166
     *
167
     * @param  int
168
     * @param  int
169
     * @return \Bedard\Shop\Models\Cart
170
     */
171
    public function setInventory($inventoryId, $quantity)
172
    {
173
        $inventory = Inventory::findOrFail($inventoryId);
174
175
        if ($quantity <= 0) {
176
            return $this->deleteItem($inventory->id);
177
        }
178
179
        $cart = $this->getCart();
180
        $item = CartItem::firstOrCreate([
181
            'cart_id' => $cart->id,
182
            'inventory_id' => $inventory->id,
183
        ]);
184
185
        $item->quantity = $quantity;
186
187
        return $item->save();
188
    }
189
190
    /**
191
     * Update multiple inventories.
192
     *
193
     * @param  array  $inventories
194
     * @return void
195
     */
196
    public function updateInventories(array $inventories)
197
    {
198
        foreach ($inventories as $inventoryId => $quantity) {
199
            $this->setInventory($inventoryId, $quantity);
200
        }
201
    }
202
203
    /**
204
     * Update a single item quantity.
205
     *
206
     * @param  int                          $itemId
207
     * @param  int                          $quantity
208
     * @return \Bedard\Shop\Models\CartItem
209
     */
210
    public function updateItem($itemId, $quantity)
211
    {
212
        $cart = $this->getCart();
213
214
        $item = $cart->items()->find($itemId);
215
216
        if ($item) {
217
            $item->quantity = $quantity;
218
            $item->save();
219
        }
220
221
        return $item;
222
    }
223
}
224