ldc-boutique-cnc/app/Models/DeliveryMode.php

119 lines
2.7 KiB
PHP
Raw Normal View History

2022-12-02 11:43:33 +01:00
<?php
namespace App\Models;
use App\Enums\DeliveryMode\DeliveryModeEnum;
2023-02-06 17:14:58 +01:00
use App\Traits\Models\HasFlashStatus;
2022-12-02 11:43:33 +01:00
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
2022-12-02 14:55:16 +01:00
use Illuminate\Support\Facades\Cache;
2022-12-02 11:43:33 +01:00
/**
*
* @property-read \App\Enums\DeliveryMode\DeliveryModeEnum $mode The delivery mode.
*
* @package App\Models
*/
class DeliveryMode extends Model
{
use HasFactory;
2023-02-06 17:14:58 +01:00
use HasFlashStatus;
2022-12-02 11:43:33 +01:00
/**
* Indicates if the IDs are auto-incrementing.
*
* @var boolean
*/
public $incrementing = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
2023-02-06 17:14:58 +01:00
'status', 'is_free',
2022-12-02 11:43:33 +01:00
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
2023-02-06 17:14:58 +01:00
'status' => 'bool',
2022-12-02 11:43:33 +01:00
'is_free' => 'bool',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted()
{
// * EVENT CLOSURES.
static::creating(function (self $model) {
throw new \RuntimeException("Creating {$model->id} is not allowed", 1);
});
2023-02-06 17:14:58 +01:00
static::created(function (self $model) {
self::flashStatus($model);
});
2022-12-02 14:55:16 +01:00
static::updated(function (self $model) {
Cache::delete('DeliveryModesGlobal');
2023-02-06 17:14:58 +01:00
self::flashStatus($model, true);
2022-12-02 14:55:16 +01:00
});
2022-12-02 11:43:33 +01:00
static::deleting(function (self $model) {
throw new \RuntimeException("Deleting {$model->id} is not allowed", 1);
});
}
// * METHODS
/**
* Getter mode
*
* @return \App\Enums\DeliveryMode\DeliveryModeEnum
*/
public function getModeAttribute(): DeliveryModeEnum
{
return DeliveryModeEnum::make(\intval($this->id));
}
/**
* Query available delivery Methods
*
* @return Builder
*/
public static function availables(): Builder
{
2023-02-08 12:12:42 +01:00
return self::where('status', true);
2022-12-02 11:43:33 +01:00
}
2022-12-02 14:55:16 +01:00
// * - Cache
/**
* Get all available delivery modes from cache.
* If cache was reset, it will fetch them from DB.
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getCachedDeliveryModes()
{
if (!Cache::has('DeliveryModesGlobal')) {
self::setCachedDeliveryModes();
}
return Cache::get('DeliveryModesGlobal');
}
/**
* Put all available delivery modes into cache.
*
* @return void
*/
protected static function setCachedDeliveryModes(): void
{
Cache::put('DeliveryModesGlobal', self::all());
}
2022-12-02 11:43:33 +01:00
}