ldc-groupe/app/Models/Document.php
2026-02-13 12:10:35 +01:00

408 lines
12 KiB
PHP

<?php
namespace App\Models;
use App\Contracts\TranslatableModel;
use App\Enums\Document\DocumentStatusEnum;
use App\Enums\YearsEnum;
use App\Helpers\DocumentHelper;
use App\Helpers\TranslationHelper;
use App\Traits\Models\HasCache;
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\Arr;
use Illuminate\Support\Facades\App;
use Laravel\Scout\Searchable;
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
/**
* @property integer $id
* Id of the document.
* @property string $name
* Name of the document.
* @property string $path
* Path of the document.
* @property boolean $is_issuu
* Issu status of the document.
* @property string $issuu_path
* Issu path of the document.
* @property string $exercice
* Exercice of the document.
* @property \App\Enums\Document\DocumentStatusEnum $status
* Status of the document.
* @property-read \Carbon\Carbon $created_at
* Created date of the document.
* @property-read \Carbon\Carbon $updated_at
* Updated date of the document.
* @property-read \Illuminate\Support\Carbon $deleted_at
* Deleted date of the document.
* @property \Illuminate\Database\Eloquent\Collection<int, \App\Models\DocumentCategory> $categories
* Associated document categories of the document.
* @property \Illuminate\Database\Eloquent\Collection<int, \App\Models\DocumentTag> $tags
* Associated document tags of the document.
*/
class Document extends Model implements TranslatableModel
{
use ActivityLog;
use HasFactory;
use HasTranslations;
use HasCache;
use HasUwilImages {
HasUwilImages::inertiaFill as traitInertiaFill;
}
use Searchable;
/**
* Champs contenant des images dynamiques à gérer.
*
* @var array
*/
protected array $imageFields = [
'path'
];
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'name',
'path',
'is_issuu',
'issuu_path',
'exercice',
'status',
'published_at',
'unpublished_at'
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'status' => DocumentStatusEnum::class,
'exercice' => YearsEnum::class,
'published_at' => 'datetime',
'unpublished_at' => 'datetime',
'is_issuu' => 'boolean',
];
/**
* The translatable columns.
*
* @var list<string>
*/
public $translatable = [
'name',
'path',
'issuu_path'
];
/**
* Relations should be included in the cache.
*
* @var list<string>
*/
protected static $cacheRelations = [
'categories',
'tags',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::creating(function (self $model) {
self::manageFields($model);
});
static::updating(function (self $model) {
self::manageFields($model);
});
}
// * METHODS
/**
* 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(DocumentStatusEnum::published)) {
$model->published_at = Carbon::now();
}
}
/**
* Getter the current status following planification dates planificated_status.
*
* @return \App\Enums\Document\DocumentStatusEnum
*/
protected function getPlanificatedStatusAttribute(): \App\Enums\Document\DocumentStatusEnum
{
/** @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()))
? DocumentStatusEnum::published
: DocumentStatusEnum::unpublished;
}
if ($published_at) {
return $published_at->lessThan(now())
? DocumentStatusEnum::published
: DocumentStatusEnum::unpublished;
}
if ($unpublished_at) {
return $unpublished_at->greaterThanOrEqualTo(now())
? DocumentStatusEnum::published
: DocumentStatusEnum::unpublished;
}
return DocumentStatusEnum::unpublished;
}
/**
* Manage model fields.
*
* @param self $model
* @return void
*/
private static function manageFields(self $model): void
{
// Check unique fields.
TranslationHelper::assertTranslationFieldIsUnique($model, $model->name, 'name');
// Check translations.
self::validateFallbackTranslations($model);
// Set status.
self::makeStatusSense($model);
}
/**
* 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(DocumentStatusEnum::published)) {
return;
}
TranslationHelper::validateFallbackTranslations($model, ['path', 'issuu_path']);
}
/**
* Get the url to access a specific resource.
*
* @param integer $id Id field of the target model.
* @return string|null
*/
public static function getAccessModel(int $id): ?string
{
$targetModel = self::getModelsCached()->firstWhere('id', $id);
if (!$targetModel) {
return null;
}
return sprintf('/%s', $targetModel->path);
}
// * MEILISEARCH
/**
* Get model's setting to apply on scout search (meilisearch).
*
* @var array
*/
public static $searchSettings = [
'filterableAttributes' => ['status'],
'sortableAttributes' => ['status']
];
/**
* Get fields that we want to keep in the current locale.
*
* @param string $currentLocale
* @return array
*/
public static function searchTransFields(string $currentLocale): array
{
return [
"name_$currentLocale",
"path_$currentLocale",
];
}
/**
* Get enum status of the model.
*
* @return integer
*/
public static function searchStatusEnum(): int
{
return DocumentStatusEnum::published->value;
}
/**
* Get front route.
*
* @return string
*/
public static function searchRouteName(): string
{
return 'front.documents.show';
}
/**
* Get model identificable field.
*
* @return string
*/
public static function searchMainField(): string
{
return 'name';
}
/**
* Get the indexable data array for the model.
*
* @return array<string, mixed>
*/
public function toSearchableArray(): array
{
$locales = config('laravellocalization.supportedLocales');
$data = [
'id' => $this->id,
'status' => $this->status->value,
];
foreach ($locales as $locale => $_) {
$data["name_$locale"] = $this->hasTranslation('name', $locale)
? $this->getTranslation('name', $locale)
: null;
$data["path_$locale"] = $this->hasTranslation('path', $locale)
? $this->getTranslation('path', $locale)
: null;
}
return $data;
}
/**
* Override HasUwilImages trait method to fill the model without relations.
*
* @param array $attributes The attributes to fill the model with.
* @return void
*/
public function inertiaFill(array $attributes): void
{
// Set issu_path if defined.
$issuuPath = data_get($attributes, "issuu_path");
if ($issuuPath) {
$attributes['issuu_path'] = DocumentHelper::extractDocumentFromIssuIframe(
data_get($attributes, "issuu_path"),
);
}
// Ommit some relations.
$attributes = Arr::except($attributes, ['tags', 'categories']);
$this->traitInertiaFill($attributes);
}
/**
* Get all published news by category.
*
* @param string $slugCategory
* @return \Illuminate\Database\Eloquent\Collection<int, \App\Models\Document>
*/
public static function getPublishedDocumentsByCategoryInCurrentLocale(
string $slugCategory,
): \Illuminate\Database\Eloquent\Collection {
$locale = App::getLocale();
return Document::getModelsCached()
->where('status', DocumentStatusEnum::published)
->filter(function ($document) use ($slugCategory, $locale) {
$hasPath = !empty($document->getTranslation('path', $locale, false));
$hasIssuuPath = $document->is_issuu === true
&& !empty($document->getTranslation('issuu_path', $locale, false));
return ($hasPath || $hasIssuuPath) && $document->categories->contains(
fn($documentCategoryModel) => $documentCategoryModel->slug === $slugCategory
);
});
}
// * RELATIONSHIPS
/**
* Relation to Tag.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function tags(): \Illuminate\Database\Eloquent\Relations\MorphToMany
{
return $this->morphedByMany(
DocumentTag::class,
'documentable',
'documentables',
'document_id',
'documentable_id'
)->withTimestamps();
}
/**
* Relation to Category.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany
*/
public function categories(): \Illuminate\Database\Eloquent\Relations\MorphToMany
{
return $this->morphedByMany(
DocumentCategory::class,
'documentable',
'documentables',
'document_id',
'documentable_id'
)->withTimestamps();
}
}