| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
-
- namespace App\Models;
-
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
- use Illuminate\Database\Eloquent\Relations\HasMany;
-
- /**
- * 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 bundles this variant is inside.
- *
- * @return HasMany<BundleItem, $this>
- */
- public function usedInBundles(): HasMany
- {
- return $this->hasMany(BundleItem::class, 'variant_id');
- }
-
- /**
- * 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',
- ];
- }
- }
|