meobda-website/app/Models/NewsStory.php

52 lines
1.5 KiB
PHP

<?php
namespace App\Models;
use App\Enums\StoryStatusEnum;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class NewsStory extends Model
{
use HasFactory;
protected $fillable = [
'headline',
'body',
'active',
'start_publication_date',
'stop_publication_date',
];
protected function casts(): array
{
return [
'active' => 'boolean',
'start_publication_date' => 'date',
'stop_publication_date' => 'date',
];
}
protected function status(): Attribute
{
return Attribute::make(
get: fn () => match (true) {
! $this->active => StoryStatusEnum::DRAFT,
$this->start_publication_date && now() < $this->start_publication_date => StoryStatusEnum::SCHEDULED,
$this->stop_publication_date && now() >= $this->stop_publication_date => StoryStatusEnum::EXPIRED,
default => StoryStatusEnum::PUBLISHED,
}
);
}
public function scopePublished($query)
{
return $query->where('active', true)
->where(fn ($q) => $q->whereNull('start_publication_date')
->orWhereDate('start_publication_date', '<=', now()))
->where(fn ($q) => $q->whereNull('stop_publication_date')
->orWhereDate('stop_publication_date', '>=', now()));
}
}