ldc-gen-game-web/app/Models/StaticPage.php
2026-10-20 12:27:49 +02:00

128 lines
3.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models;
use App\Enums\StaticPageType;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\HasActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
/**
* @property StaticPageType $type Page type (StaticPageEnum).
* @property string $seo_title Seo title about 70 chars as recommended.
* @property string $seo_description Seo description about 160 chars as recommended.
* @property string $title Title for the page.
* @property string $slug Slug of the title for the page.
* @property string $content WYSIWYG text content using ckeditor.
* @property-read Carbon $created_at Created date.
* @property-read Carbon $updated_at Updated date.
* @property-read \App\Models\ActivityLog $activityLogs Activities logs One-to-many relationship.
*/
class StaticPage extends Model
{
use HasActivityLog;
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
#[\Override]
protected $fillable = [
'seo_title',
'seo_description',
'title',
'content',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
#[\Override]
protected $casts = [
'type' => StaticPageType::class,
];
// * EVENTS
/**
* Perform any actions required after the model boots.
*/
protected static function booted(): void
{
static::creating(function (self $model): void {
// * ASSERTIONS
self::assertTitleIsUnique($model->title);
// * CHANGES
$model->slug = Str::slug($model->title);
});
static::updating(function (self $model): void {
// * ASSERTIONS
self::assertTitleIsUnique($model->title, $model->id);
// * CHANGES
$model->slug = Str::slug($model->title);
});
}
// * ROUTABLE
/**
* Get the value of the model's route key.
*
* @return mixed
*/
public function getRouteKey()
{
/** @var StaticPageType */
$enum = $this->getAttribute($this->getRouteKeyName());
return $enum->value();
}
/**
* Get the route key for the model.
*
* ! Type is the routable parameter
*/
public function getRouteKeyName(): string
{
return 'type';
}
// * METHODS
/**
* Asserts using validation that the title is unique
*
*
* @throws ValidationException If an actu title already exists.
*/
private static function assertTitleIsUnique(?string $title, ?int $id = null): void
{
$table = new self()->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id);
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id);
}
// * RELATIONS
/**
* Activities logs One-to-many relationship.
*
* @return HasMany<ActivityLog, $this>
*/
public function activityLogs(): HasMany
{
return $this->hasMany(ActivityLog::class);
}
}