| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- <?php
-
- namespace App\Models;
-
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
-
- /**
- * One combination of a product's options, such as "500g / Pedas", with its own price and stock.
- * Prices are in sen (1 ringgit = 100 sen).
- *
- * @property int $id
- * @property int $store_id
- * @property int $product_id
- * @property string $option1
- * @property string|null $option2
- * @property int $price
- * @property int|null $compare_at_price
- * @property int $stock
- * @property int $position
- * @property-read Product $product
- */
- class ProductVariant extends Model
- {
- /**
- * @return BelongsTo<Product, $this>
- */
- public function product(): BelongsTo
- {
- return $this->belongsTo(Product::class);
- }
-
- /**
- * The option values in order, without empty ones.
- *
- * @return list<string>
- */
- public function values(): array
- {
- return array_values(array_filter([$this->option1, $this->option2], fn (?string $value) => $value !== null && $value !== ''));
- }
-
- /**
- * "500g / Pedas".
- */
- public function name(): string
- {
- return implode(' / ', $this->values());
- }
-
- /**
- * What the storefront is allowed to see. Prices are in ringgit here.
- *
- * @return array<string, mixed>
- */
- public function toStorefront(): array
- {
- return [
- 'id' => $this->id,
- 'name' => $this->name(),
- 'options' => $this->values(),
- 'price' => $this->price / 100,
- 'compare_at_price' => $this->compare_at_price !== null ? $this->compare_at_price / 100 : null,
- 'in_stock' => $this->stock > 0,
- 'stock_left' => $this->stock,
- ];
- }
-
- /**
- * @return array<string, string>
- */
- protected function casts(): array
- {
- return [
- 'price' => 'integer',
- 'compare_at_price' => 'integer',
- 'stock' => 'integer',
- 'position' => 'integer',
- ];
- }
- }
|