| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
-
- namespace App\Models;
-
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
-
- /**
- * One thing inside a bundle: a product (and, for a product with options, one of its variants) and how many.
- *
- * @property int $id
- * @property int $store_id
- * @property int $bundle_id
- * @property int $product_id
- * @property int|null $variant_id
- * @property int $quantity
- * @property int $position
- * @property-read Product $bundle
- * @property-read Product $product
- * @property-read ProductVariant|null $variant
- */
- class BundleItem extends Model
- {
- /**
- * @return BelongsTo<Product, $this>
- */
- public function bundle(): BelongsTo
- {
- return $this->belongsTo(Product::class, 'bundle_id');
- }
-
- /**
- * @return BelongsTo<Product, $this>
- */
- public function product(): BelongsTo
- {
- return $this->belongsTo(Product::class);
- }
-
- /**
- * @return BelongsTo<ProductVariant, $this>
- */
- public function variant(): BelongsTo
- {
- return $this->belongsTo(ProductVariant::class, 'variant_id');
- }
-
- /**
- * Make a bundle hold exactly these items, in this order. Not a bundle: pass an empty list.
- *
- * @param list<array{product_id: int, variant_id: int|null, quantity: int}> $items
- */
- public static function replaceFor(Product $bundle, array $items): void
- {
- $bundle->bundleItems()->delete();
-
- foreach ($items as $position => $item) {
- $row = new self;
- $row->store_id = $bundle->store_id;
- $row->bundle_id = $bundle->id;
- $row->product_id = $item['product_id'];
- $row->variant_id = $item['variant_id'];
- $row->quantity = $item['quantity'];
- $row->position = $position;
- $row->save();
- }
-
- $bundle->unsetRelation('bundleItems');
- }
-
- /**
- * "Sambal Hijau (250g)".
- */
- public function name(): string
- {
- return $this->product->name.($this->variant !== null ? ' ('.$this->variant->name().')' : '');
- }
-
- /**
- * "2 × Sambal Hijau (250g)".
- */
- public function label(): string
- {
- return $this->quantity.' × '.$this->name();
- }
-
- /**
- * How many of this item are left: the variant's stock, or the product's.
- */
- public function stock(): int
- {
- return $this->variant !== null ? $this->variant->stock : $this->product->stock;
- }
-
- /**
- * @return array<string, string>
- */
- protected function casts(): array
- {
- return [
- 'quantity' => 'integer',
- 'position' => 'integer',
- ];
- }
- }
|