1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Treestoneit\ShoppingCart; |
4
|
|
|
|
5
|
|
|
// TODO When session is destroyed, delete cart not attached to user |
6
|
|
|
|
7
|
|
|
use Countable; |
8
|
|
|
use Illuminate\Contracts\Auth\Authenticatable; |
9
|
|
|
use Illuminate\Support\Traits\ForwardsCalls; |
10
|
|
|
use Illuminate\Support\Traits\Macroable; |
11
|
|
|
use Treestoneit\ShoppingCart\Models\Cart; |
12
|
|
|
|
13
|
|
|
class CartManager implements Countable, CartContract |
14
|
|
|
{ |
15
|
|
|
use Concerns\ManagesCartItems; |
16
|
|
|
use Concerns\CalculatesTotals; |
17
|
|
|
use Concerns\AttachesToUsers; |
18
|
|
|
use ForwardsCalls; |
19
|
|
|
use Macroable { |
20
|
|
|
__call as macroCall; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* CartManager constructor. |
25
|
|
|
* |
26
|
|
|
* @param \Treestoneit\ShoppingCart\Models\Cart|\Illuminate\Database\Eloquent\Model $cart |
27
|
|
|
*/ |
28
|
|
|
public function __construct(Cart $cart) |
29
|
|
|
{ |
30
|
|
|
$this->cart = $cart; |
31
|
|
|
|
32
|
|
|
$this->refreshCart(); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Instantiate the cart manager with a cart id saved in the current session. |
37
|
|
|
* |
38
|
|
|
* @param string $identifier |
39
|
|
|
* @return static |
40
|
|
|
*/ |
41
|
|
|
public static function fromSessionIdentifier($identifier): self |
42
|
|
|
{ |
43
|
|
|
$cart = Cart::findOrNew($identifier); |
44
|
|
|
|
45
|
|
|
return new static($cart); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Instantiate the cart manager with the cart attached to the currently authenticated user. |
50
|
|
|
* |
51
|
|
|
* @param \Illuminate\Contracts\Auth\Authenticatable $user |
52
|
|
|
* @return static |
53
|
|
|
*/ |
54
|
|
|
public static function fromUserId(Authenticatable $user): self |
55
|
|
|
{ |
56
|
|
|
return new static(Cart::where('user_id', $user->getAuthIdentifier())->firstOrNew([ |
57
|
|
|
'user_id' => $user->getAuthIdentifier(), |
58
|
|
|
])); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Pass dynamic method calls to the items collection. |
63
|
|
|
* |
64
|
|
|
* @param string $method |
65
|
|
|
* @param array $arguments |
66
|
|
|
* @return mixed |
67
|
|
|
*/ |
68
|
|
|
public function __call($method, $arguments) |
69
|
|
|
{ |
70
|
|
|
if (static::hasMacro($method)) { |
71
|
|
|
return $this->macroCall($method, $arguments); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $this->forwardCallTo($this->items(), $method, $arguments); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|