ldc-legaulois/app/Models/NewsBreeding.php
2025-01-08 10:40:21 +01:00

240 lines
7.6 KiB
PHP

<?php
namespace App\Models;
use App\Enums\StaticPageType;
use App\Lib\Helpers\FileStorageHelper;
use App\Lib\Helpers\ToolboxHelper;
use App\Traits\Models\ActivityLog;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Laravel\Scout\Searchable;
/**
* @property string $title The title of the bredding news.
* @property string $slug The slug of the bredding news.
* @property string $subtitle The subtitle of the bredding news.
* @property string $content The content of the bredding news.
* @property string $picture Picture path.
* @property string $picture_title Picture title attribute.
* @property string $picture_alt Picture alt attribute.
* @property \App\Enums\StaticPageType $associated_page The associated page.
* @property int $order Order.
* @property boolean $published Bredding news publish status.
* @property-read \Carbon\Carbon $published_at Bredding news published_at.
* @property-read \Carbon\Carbon $unpublished_at Bredding news unpublished_at.
* @property-read \Carbon\Carbon $created_at Created date.
* @property-read \Carbon\Carbon $updated_at Updated date.
*/
class NewsBreeding extends Model
{
use ActivityLog;
use HasFactory;
use Searchable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'seo_title',
'seo_description',
'title',
'subtitle',
'content',
'slug',
'picture',
'picture_alt',
'picture_title',
'associated_page',
'order',
'published',
'publish_at',
'unpublish_at',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'published' => 'boolean',
'publish_at' => 'datetime',
'unpublish_at' => 'datetime',
'associated_page' => StaticPageType::class,
];
/**
* Get model's setting to apply on scout search (meilisearch).
*
* @return array
*/
public static $searchSettings = [
'filterableAttributes' => ['title', 'content', 'published'],
'sortableAttributes' => ['title', 'content']
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
self::setOrder($model);
self::manageFields($model);
});
static::created(function (self $model) {
self::resetCache($model->associated_page);
});
static::updating(function (self $model) {
self::manageFields($model);
});
static::updated(function (self $model) {
FileStorageHelper::removeOldFile($model, 'picture');
self::resetCache($model->associated_page);
});
static::deleted(function (self $model) {
FileStorageHelper::removeFile($model, 'picture');
self::resetCache($model->associated_page);
});
}
// * METHODS
/**
* Manage model fields.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model): void
{
self::assertTitleIsUnique($model->title, $model->getKey() ?? null);
$model->slug = Str::slug($model->title);
self::makeStatusSense($model);
$model->picture = FileStorageHelper::storeFile($model, $model->picture, true);
}
/**
* Set order after the last element of the list.
*
* @param self $model
* @return void
*/
private static function setOrder(self $model): void
{
$model->order = \intval(self::query()->max('order')) + 1;
}
/**
* Adjusts breedingNews status using current status and publish dates.
*
* @param self $model
* @return void
*/
private static function makeStatusSense(self $model): void
{
/** @var \Carbon\Carbon|null */
$publish_at = $model->publish_at;
/** @var \Carbon\Carbon|null */
$unpublish_at = $model->unpublish_at;
$wantedStatus = $model->published;
if ($publish_at or $unpublish_at) {
$model->published = $model->planificated_status;
}
if ($wantedStatus !== $model->published) {
session()->flash('bo.info', \trans(
'La publication est modifiée en concordance avec les dates enregistrées.
Pour modifier l\'état de publication, veuillez modifier ou enlever les dates correspondantes.'
));
}
}
/**
* Asserts using validation that the title is unique.
*
* @param string|null $title
* @param integer|null $id
* @return void
* @throws \Illuminate\Validation\ValidationException If an actu title already exists.
*/
private static function assertTitleIsUnique(string|null $title, ?int $id = null): void
{
$table = (new self())->getTable();
ToolboxHelper::assertFieldIsUnique($table, 'title', $title, $id);
ToolboxHelper::assertFieldIsUnique($table, 'slug', Str::slug($title), $id);
}
/**
* Getter the current status following planification dates planificated_status.
*
* @return boolean
*/
public function getPlanificatedStatusAttribute(): bool
{
/** @var \Carbon\Carbon|null */
$publish_at = $this->publish_at;
/** @var \Carbon\Carbon|null */
$unpublish_at = $this->unpublish_at;
if ($publish_at and $unpublish_at) {
return $unpublish_at->greaterThanOrEqualTo(now()) and $publish_at->lessThan(now());
}
if ($publish_at) {
return $publish_at->lessThan(now());
}
if ($unpublish_at) {
return $unpublish_at->greaterThanOrEqualTo(now());
}
return false;
}
/**
* Reset all cache elements related to this model.
*
* @param \App\Enums\StaticPageType $type
* @return void
*/
private static function resetCache(StaticPageType $type): void
{
Cache::forget(sprintf('%sPublishedNewsBreedingOrderedByOrder', $type->name));
self::getPublishedOrderedForType($type);
}
/**
* Get all published news breeding ordered by order associated to a given static page type.
*
* @param \App\Enums\StaticPageType $type
* @return \Illuminate\Database\Eloquent\Collection
*/
public static function getPublishedOrderedForType(StaticPageType $type): \Illuminate\Database\Eloquent\Collection
{
return Cache::rememberForever(
sprintf('%sPublishedNewsBreedingOrderedByOrder', $type->name),
fn() =>
self::query()
->where('associated_page', $type)
->where('published', true)
->orderBy('order')
->get()
);
}
// * RELATIONSHIPS
/**
* Get Breeding static page (one-to-many relationship).
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function breedingPages(): \Illuminate\Database\Eloquent\Relations\BelongsTo
{
return $this->belongsTo(StaticPage::class)->where('type', 'breeding%');
}
}