| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183 |
- <?php
-
- namespace App\Commerce;
-
- use App\Models\Product;
- use App\Models\Store;
- use Illuminate\Contracts\Session\Session;
- use Illuminate\Support\Collection;
-
- /**
- * A shopper's cart for one store.
- *
- * It is kept in the browser session, so shoppers do not need an account, and each store
- * has its own cart. Only product ids and quantities are saved. Names, prices and stock are
- * always read fresh from the database, so the cart can never show an old price.
- */
- class Cart
- {
- /** The most of one product a shopper may put in the cart. */
- public const int MAX_QUANTITY = 99;
-
- /** True when a quantity was lowered or an item dropped while loading, because stock or status changed. */
- private bool $adjusted = false;
-
- public function __construct(
- private readonly Session $session,
- private readonly Store $store,
- ) {}
-
- /**
- * Put more of a product in the cart. Returns how many are in the cart afterwards.
- */
- public function add(Product $product, int $quantity): int
- {
- return $this->store(($this->quantities()[$product->id] ?? 0) + $quantity, $product);
- }
-
- /**
- * Set exactly how many of a product are in the cart. Zero removes it.
- * The number is capped by the stock and by MAX_QUANTITY.
- */
- public function set(Product $product, int $quantity): int
- {
- return $this->store($quantity, $product);
- }
-
- private function store(int $wanted, Product $product): int
- {
- $quantities = $this->quantities();
- $allowed = max(0, min($wanted, $product->stock, self::MAX_QUANTITY));
-
- if ($allowed === 0) {
- unset($quantities[$product->id]);
- } else {
- $quantities[$product->id] = $allowed;
- }
-
- $this->save($quantities);
-
- return $allowed;
- }
-
- public function remove(int $productId): void
- {
- $quantities = $this->quantities();
- unset($quantities[$productId]);
-
- $this->save($quantities);
- }
-
- public function clear(): void
- {
- $this->session->forget($this->key());
- }
-
- /**
- * The cart lines, with fresh product details.
- * Products that are no longer for sale are dropped, and quantities above the stock are lowered.
- *
- * @return Collection<int, array{product: Product, quantity: int, line_total: int}>
- */
- public function lines(): Collection
- {
- $quantities = $this->quantities();
-
- if ($quantities === []) {
- return collect();
- }
-
- $products = $this->store->products()
- ->active()
- ->with('images')
- ->whereKey(array_keys($quantities))
- ->get()
- ->keyBy('id');
-
- $kept = [];
- $lines = collect();
-
- foreach ($quantities as $productId => $quantity) {
- $product = $products->get($productId);
- $allowed = $product ? min($quantity, $product->stock, self::MAX_QUANTITY) : 0;
-
- if ($allowed !== $quantity) {
- $this->adjusted = true;
- }
-
- if ($product === null || $allowed < 1) {
- continue;
- }
-
- $kept[$productId] = $allowed;
- $lines->push([
- 'product' => $product,
- 'quantity' => $allowed,
- 'line_total' => $product->price * $allowed,
- ]);
- }
-
- if ($kept !== $quantities) {
- $this->save($kept);
- }
-
- return $lines;
- }
-
- /**
- * What the storefront is allowed to see. Money is in ringgit here.
- *
- * @return array{count: int, subtotal: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
- */
- public function toStorefront(): array
- {
- $lines = $this->lines();
-
- return [
- 'count' => (int) $lines->sum('quantity'),
- 'subtotal' => $lines->sum('line_total') / 100,
- 'adjusted' => $this->adjusted,
- 'lines' => $lines->map(fn (array $line) => [
- 'product' => $line['product']->toStorefront(),
- 'quantity' => $line['quantity'],
- 'max' => min($line['product']->stock, self::MAX_QUANTITY),
- 'line_total' => $line['line_total'] / 100,
- ])->values()->all(),
- ];
- }
-
- /**
- * @return array<int, int> Product id to quantity.
- */
- private function quantities(): array
- {
- $saved = $this->session->get($this->key(), []);
-
- if (! is_array($saved)) {
- return [];
- }
-
- $clean = [];
-
- foreach ($saved as $productId => $quantity) {
- if (is_int($productId) && is_int($quantity) && $quantity > 0) {
- $clean[$productId] = $quantity;
- }
- }
-
- return $clean;
- }
-
- /**
- * @param array<int, int> $quantities
- */
- private function save(array $quantities): void
- {
- $this->session->put($this->key(), $quantities);
- }
-
- private function key(): string
- {
- return 'cart.'.$this->store->id;
- }
- }
|