1<?php ...
2
3namespace Thunk\Verbs\Examples\Cart\Events;
4
5use Thunk\Verbs\Event;
6use Thunk\Verbs\Examples\Cart\States\CartState;
7use Thunk\Verbs\Examples\Cart\States\ItemState;
8
9class ItemAddedToCart extends Event
10{
11 public static int $item_limit = 2;
12
13 public static int $hold_seconds = 5;
14
15 public ItemState $item;
16
17 public CartState $cart;
18
19 public int $quantity;
20
21 public function validate()
22 {
23 $this->assert(! $this->cart->checked_out, 'Already checked out');
24
25 $this->assert(
26 $this->item->available() >= $this->quantity,
27 'Out of stock',
28 );
29
30 $this->assert(
31 $this->cart->count($this->item->id) + $this->quantity <= self::$item_limit,
32 'Reached limit'
33 );
34 }
35
36 public function apply()
37 {
38 // Add (additional?) quantity to cart
39 $this->cart->items[$this->item->id] = $this->cart->count($this->item->id) + $this->quantity;
40
41 // Initialize hold to 0 if it doesn't already exist
42 $this->item->holds[$this->cart->id] ??= [
43 'quantity' => 0,
44 'expires' => now()->unix() + self::$hold_seconds,
45 ];
46
47 // Add quantity to hold
48 $this->item->holds[$this->cart->id]['quantity'] += $this->quantity;
49 }
50}