ldc-groupe/app/Models/News.php
2025-12-01 14:51:11 +01:00

340 lines
10 KiB
PHP

<?php
namespace App\Models;
use App\Contracts\TranslatableModel;
use App\Enums\News\NewsStatusEnum;
use App\Helpers\TranslationHelper;
use App\Traits\Models\HasTranslations;
use App\Traits\Models\HasUwilImages;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\SoftDeletes;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
/**
* @property string $seo_title SEO title of the news.
* @property string $seo_description SEO description of the news.
* @property string $title Title of the news.
* @property string $slug Slug of the news.
* @property string $picture Main img of the news.
* @property string $picture_alt Alt text for the picture.
* @property string $picture_title Title for the picture.
* @property string $content Content of the news.
* @property boolean $inverted Are image and content inverted in front
* @property string $vimeo_id Optionnal vimeo_id
* @property boolean $has_show_picture Show the picture in the show page
* @property \App\Enums\News\NewsStatusEnum $status Status of the news.
* @property-read \Illuminate\Support\Carbon $created_at Date on which the news was created.
* @property-read \Illuminate\Support\Carbon $updated_at Date on which the news was updated.
* @property-read \Illuminate\Support\Carbon $deleted_at Date on which the news was updated.
*/
class News extends Model implements TranslatableModel
{
use ActivityLog;
use HasFactory;
use HasTranslations;
use SoftDeletes;
use HasUwilImages {
HasUwilImages::inertiaFill as traitInertiaFill;
}
/**
* Champs contenant des images dynamiques à gérer.
*
* @var array
*/
protected array $imageFields = [
'picture'
];
/**
* Champs contenant des wysiwyg avec images dynamiques à gérer.
*
* @var array
*/
protected array $wysiwygFields = [
'content'
];
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'seo_title',
'seo_description',
'title',
'slug',
'content',
'status',
'picture',
'picture_alt',
'picture_title',
'published_at',
'unpublished_at',
'inverted',
'vimeo_id',
'has_show_picture'
];
/**
* The translatable columns.
*
* @var list<string>
*/
public $translatable = [
'seo_title',
'seo_description',
'title',
'slug',
'content',
'picture_alt',
'picture_title',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'status' => NewsStatusEnum::class,
'published_at' => 'datetime',
'unpublished_at' => 'datetime',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
self::manageFields($model);
});
static::created(function (self $model) {
self::resetCache();
});
static::updating(function (self $model) {
self::manageFields($model);
});
static::updated(function (self $model) {
self::resetCache();
});
static::deleted(function () {
self::resetCache();
});
static::restoring(function (self $model) {
self::resetCache();
$model->status = NewsStatusEnum::unpublished;
});
static::forceDeleted(function (self $model) {
self::resetCache();
});
}
// * METHODS
/**
* Manage model fields.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model): void
{
// Check unique fields.
$slug = Str::slug($model->title);
TranslationHelper::assertTranslationFieldIsUnique($model, $model->title, 'title');
TranslationHelper::assertTranslationFieldIsUnique($model, $slug, 'slug', 'title');
$model->setAttribute('slug', $slug);
// Check translations.
self::validateFallbackTranslations($model);
// Set status.
self::makeStatusSense($model);
}
public function inertiaFill(array $attributes)
{
$attributes = Arr::except($attributes, ['categories']);
$this->traitInertiaFill($attributes);
}
/**
* Adjusts model status using current status and publish dates.
* Case 1: publish model when all null -> set published_at date.
* Case 2: unpublish model when all null -> nothing to do.
* Case 3: publish model when published_at is already set -> only change status.
* Case 4: unpublish model when published_at is already set -> can't update model.
* Case 5: publish model when unpublished_at is already set -> can't update model.
* Case 6: unpublish model when unpublished_at is already set -> only change status.
*
* @param self $model
* @return void
*/
private static function makeStatusSense(self $model): void
{
/** @var \Carbon\Carbon|null */
$published_at = $model->published_at;
/** @var \Carbon\Carbon|null */
$unpublished_at = $model->unpublished_at;
$wantedStatus = $model->status;
// Check if dates are already set.
if ($published_at or $unpublished_at) {
$model->status = $model->planificated_status;
}
// If there is a diff, no update.
if ($wantedStatus !== $model->status) {
session()->flash('error', \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.'
));
}
// Set default published_at date when publishing model.
if (!$published_at && $model->status->equals(NewsStatusEnum::published)) {
$model->published_at = Carbon::now();
}
}
/**
* Getter the current status following planification dates planificated_status.
*
* @return \App\Enums\News\NewsStatusEnum
*/
protected function getPlanificatedStatusAttribute(): \App\Enums\News\NewsStatusEnum
{
/** @var \Carbon\Carbon|null */
$published_at = $this->published_at;
/** @var \Carbon\Carbon|null */
$unpublished_at = $this->unpublished_at;
if ($published_at and $unpublished_at) {
return ($unpublished_at->greaterThanOrEqualTo(now()) and $published_at->lessThan(now()))
? NewsStatusEnum::published
: NewsStatusEnum::unpublished;
}
if ($published_at) {
return $published_at->lessThan(now())
? NewsStatusEnum::published
: NewsStatusEnum::unpublished;
}
if ($unpublished_at) {
return $unpublished_at->greaterThanOrEqualTo(now())
? NewsStatusEnum::published
: NewsStatusEnum::unpublished;
}
return NewsStatusEnum::unpublished;
}
/**
* Reset all cache elements related to this model.
*
* @return void
*/
public static function resetCache(): void
{
Cache::forget('getPublishedNews');
self::getPublishedNews();
}
/**
* Get all published news.
*
* @return \Illuminate\Database\Eloquent\Collection<int,self>
*/
public static function getPublishedNews(): \Illuminate\Database\Eloquent\Collection
{
return Cache::remember('getPublishedNews', 86400, function () {
return self::query()
->where('status', NewsStatusEnum::published)
->with('categories')
->get();
});
}
/**
* Get formated published_at date.
*
* @return string
*/
public function publishedAtFormatted(): string
{
return Carbon::parse($this->published_at)->format('d/m/Y');
}
/**
* Get a comma-separated list of all category labels for this news item.
*
* @return string|null
*/
public function getCategoryLabelsAttribute(): ?string
{
if (empty($this->categories)) {
return null;
}
$labels = collect($this->categories)
->map(fn($cat) => $cat->category->label() ?? null)
->filter()
->values();
return $labels->join(', ');
}
/**
* Get data related to the first category of this news item.
*
* @return array<string, string>|null>
*/
public function getFirstCategoryDataAttribute(): ?array
{
if (empty($this->categories) || empty($this->categories[0])) {
return null;
}
$cat = $this->categories[0]->category;
return [
'category_classes' => $cat->getClasses(),
'date_classes' => $cat->getDateClasses(),
'label' => $cat->label(),
];
}
/**
* Assert fallback locale translation is present.
*
* @param self $model
* @return void
* @throws \Illuminate\Validation\ValidationException Translations missing.
*/
public static function validateFallbackTranslations(self $model): void
{
if (!$model->status->equals(NewsStatusEnum::published)) {
return;
}
TranslationHelper::validateFallbackTranslations($model);
}
// * RELATIONSHIPS
/**
* The relation with NewsCategory.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function categories(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(NewsCategory::class, 'news_id');
}
}