1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Treestoneit\ShoppingCart\Concerns; |
4
|
|
|
|
5
|
|
|
use Illuminate\Contracts\Auth\Authenticatable; |
6
|
|
|
use Treestoneit\ShoppingCart\Models\Cart as CartModel; |
7
|
|
|
|
8
|
|
|
trait AttachesToUsers |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* Load the given user's shopping cart. |
12
|
|
|
* |
13
|
|
|
* @param \Illuminate\Contracts\Auth\Authenticatable $user |
14
|
|
|
* @return static |
15
|
|
|
*/ |
16
|
|
|
public function loadUserCart(Authenticatable $user): self |
17
|
|
|
{ |
18
|
|
|
// If the user doesn't yet have a saved cart, we'll |
19
|
|
|
// just attach the current one to the user and exit. |
20
|
|
|
if (! $cart = CartModel::whereUserId($user->getAuthIdentifier())->with('items')->first()) { |
21
|
|
|
return $this->attachTo($user); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
// If the current cart is empty, we'll load the saved one. |
25
|
|
|
if ($this->items()->isEmpty()) { |
|
|
|
|
26
|
|
|
return $this->refreshCart($cart); |
|
|
|
|
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
// Otherwise, we'll overwrite the saved cart with the current one. |
30
|
|
|
// TODO add a strategy to be able to merge with the saved cart |
31
|
|
|
return $this->overwrite($user); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Attach the current cart to the given user. |
36
|
|
|
* |
37
|
|
|
* @param \Illuminate\Contracts\Auth\Authenticatable $user |
38
|
|
|
* @return static |
39
|
|
|
*/ |
40
|
|
|
public function attachTo(Authenticatable $user): self |
41
|
|
|
{ |
42
|
|
|
$this->cart->fill([ |
|
|
|
|
43
|
|
|
'user_id' => $user->getAuthIdentifier(), |
44
|
|
|
]); |
45
|
|
|
|
46
|
|
|
if ($this->cart->exists) { |
47
|
|
|
$this->cart->save(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return $this; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Delete any old carts belonging to the given user and attach |
55
|
|
|
* the current cart to them. |
56
|
|
|
* |
57
|
|
|
* @param \Illuminate\Contracts\Auth\Authenticatable $user |
58
|
|
|
* @return static |
59
|
|
|
*/ |
60
|
|
|
protected function overwrite(Authenticatable $user): self |
61
|
|
|
{ |
62
|
|
|
CartModel::whereUserId($user->getAuthIdentifier()) |
|
|
|
|
63
|
|
|
->whereKeyNot($this->cart->getKey()) |
64
|
|
|
// Delete them using Eloquent so that events will be fired |
65
|
|
|
// and trigger deletion of cart items as well. |
66
|
|
|
->get()->each->delete(); |
67
|
|
|
|
68
|
|
|
return $this->attachTo($user); |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
This check looks for methods that are used by a trait but not required by it.
To illustrate, let’s look at the following code example
The trait
Idable
provides a methodequalsId
that in turn relies on the methodgetId()
. If this method does not exist on a class mixing in this trait, the method will fail.Adding the
getId()
as an abstract method to the trait will make sure it is available.