119 lines
3 KiB
PHP
119 lines
3 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Enums\Claims\ClaimMessageType;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
/**
|
|
* @property integer $id Subject id.
|
|
* @property string $label Subject label.
|
|
* @property \App\Models\Claim $claim_id Subject associated Claim.
|
|
* @property-read \Illuminate\Support\Carbon $created_at Subject created date.
|
|
* @property-read \Illuminate\Support\Carbon $updated_at Subject updated date.
|
|
*/
|
|
class ClaimMessage extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var array<int, string>
|
|
*/
|
|
protected $fillable = [
|
|
'content',
|
|
'type',
|
|
'claim_id',
|
|
'user_id',
|
|
];
|
|
|
|
/**
|
|
* The attributes that should be cast.
|
|
*
|
|
* @var array<string, mixed>
|
|
*/
|
|
protected $casts = [
|
|
'type' => ClaimMessageType::class,
|
|
];
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted(): void
|
|
{
|
|
static::created(function () {
|
|
self::resetCache();
|
|
});
|
|
static::updated(function () {
|
|
self::resetCache();
|
|
});
|
|
static::deleted(function () {
|
|
self::resetCache();
|
|
});
|
|
}
|
|
|
|
// * METHODS
|
|
|
|
/**
|
|
* Get all brands associated to the auth user.
|
|
*
|
|
* @param integer $claimModelKey
|
|
* @return \Illuminate\Database\Eloquent\Collection
|
|
*/
|
|
public static function getAllModelsFromClaim(int $claimModelKey): \Illuminate\Database\Eloquent\Collection
|
|
{
|
|
return self::getClaimMessages()->filter(
|
|
fn($model) => $model->claim->getKey() === $claimModelKey
|
|
)->values();
|
|
}
|
|
|
|
/**
|
|
* Reset all cache elements related to this model.
|
|
*
|
|
* @return void
|
|
*/
|
|
private static function resetCache(): void
|
|
{
|
|
Cache::forget('claimMessages');
|
|
self::getClaimMessages();
|
|
}
|
|
|
|
/**
|
|
* Get all brands.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Collection
|
|
*/
|
|
public static function getClaimMessages(): \Illuminate\Database\Eloquent\Collection
|
|
{
|
|
return Cache::remember('claimMessages', 86400, function () {
|
|
return self::query()->with('user')->orderby('created_at', 'ASC')->get();
|
|
});
|
|
}
|
|
|
|
// * RELATIONS
|
|
|
|
/**
|
|
* Claim belongs to relation.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
|
*/
|
|
public function claim(): \Illuminate\Database\Eloquent\Relations\BelongsTo
|
|
{
|
|
return $this->belongsTo(Claim::class);
|
|
}
|
|
|
|
/**
|
|
* User belongs to relation.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
|
|
*/
|
|
public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
|
|
{
|
|
return $this->belongsTo(User::class);
|
|
}
|
|
}
|