377 lines
12 KiB
PHP
377 lines
12 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Contracts\TranslatableModel;
|
|
use App\Enums\DynamicFieldTypes;
|
|
use App\Enums\DynamicPages\PageStatusEnum;
|
|
use App\Helpers\DynamicPageHelper;
|
|
use App\Helpers\RouteHelper;
|
|
use App\Helpers\TranslationHelper;
|
|
use App\Traits\Models\HasCache;
|
|
use App\Traits\Models\HasTranslations;
|
|
use App\Traits\Models\HasUwilImages;
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Uwil\LaravelActivityLogs\Traits\ActivityLog;
|
|
use Uwil\LaravelCommon\Helpers\FileHelper;
|
|
|
|
/**
|
|
* @property string $id_key Unique key identification of the dynamic page.
|
|
* @property string $title Title of the dynamic page.
|
|
* @property string $slug Slug of the dynamic page.
|
|
* @property string $content Content of the dynamic page.
|
|
* @property integer|null $config_id Config associated to the dynamic page.
|
|
* @property integer|null $page_id Page associated to the dynamic page.
|
|
* @property \App\Enums\DynamicPages\PageStatusEnum $status Status of the dynamic page.
|
|
* @property boolean $isLocked Locked status of dynamic page.
|
|
* @property boolean $isRoot Root status of dynamic page.
|
|
* @property-read \Illuminate\Support\Carbon $created_at Date on which the dynamic page was created.
|
|
* @property-read \Illuminate\Support\Carbon $updated_at Date on which the dynamic page was updated.
|
|
* @property-read \Illuminate\Support\Carbon $deleted_at Date on which the dynamic page was updated.
|
|
*/
|
|
class DynamicPage extends Model implements TranslatableModel
|
|
{
|
|
use ActivityLog;
|
|
use HasCache;
|
|
use HasFactory;
|
|
use HasTranslations;
|
|
use HasUwilImages;
|
|
use SoftDeletes;
|
|
|
|
/**
|
|
* The attributes that are mass assignable.
|
|
*
|
|
* @var list<string>
|
|
*/
|
|
protected $fillable = [
|
|
'id_key',
|
|
'title',
|
|
'slug',
|
|
'content',
|
|
'page_id',
|
|
'config_id',
|
|
'status',
|
|
'isLocked',
|
|
'isRoot',
|
|
];
|
|
|
|
/**
|
|
* The attributes that should be cast.
|
|
*
|
|
* @var array<string, string>
|
|
*/
|
|
protected $casts = [
|
|
'content' => 'array',
|
|
'status' => PageStatusEnum::class,
|
|
'isLocked' => 'boolean',
|
|
'isRoot' => 'boolean',
|
|
];
|
|
|
|
/**
|
|
* The translatable columns.
|
|
*
|
|
* @var list<string>
|
|
*/
|
|
public $translatable = [
|
|
'slug',
|
|
'title',
|
|
'content',
|
|
];
|
|
|
|
/**
|
|
* Relations should be included in the cache.
|
|
*
|
|
* @var array<string, string>
|
|
*/
|
|
protected static $cacheRelations = [
|
|
'config',
|
|
'parentPage',
|
|
'childPages',
|
|
];
|
|
|
|
/**
|
|
* Perform any actions required after the model boots.
|
|
*
|
|
* @return void
|
|
*/
|
|
protected static function booted(): void
|
|
{
|
|
static::creating(function (self $model) {
|
|
self::manageFields($model);
|
|
$model->id_key = $model->slug;
|
|
});
|
|
static::updating(function (self $model) {
|
|
self::manageFields($model);
|
|
self::checkParentsStatus($model);
|
|
});
|
|
static::updated(function (self $model) {
|
|
self::setAllChildPageStatus($model);
|
|
// TODO: update this after recursive deleting images.
|
|
// DynamicPageHelper::removeImgs($model);
|
|
});
|
|
static::restoring(function (self $model) {
|
|
if ($model->config_id && $model->config()->onlyTrashed()->exists()) {
|
|
throw ValidationException::withMessages([
|
|
'error' => trans('crud.messages.cannot_be_restored', [
|
|
'model' => Str::ucfirst(trans_choice('models.classes.dynamic-page', 1))
|
|
]),
|
|
]);
|
|
}
|
|
$model->status = PageStatusEnum::draft;
|
|
$model->isRoot = false;
|
|
});
|
|
static::forceDeleted(function (self $model) {
|
|
// TODO: update this after recursive deleting images.
|
|
// DynamicPageHelper::removeImgs($model, true);
|
|
});
|
|
}
|
|
|
|
// * METHODS
|
|
|
|
/**
|
|
* Store recursively all uploaded files in array.
|
|
* Overwrite trait method to filter fields with image_ prefix.
|
|
*
|
|
* @return array
|
|
*/
|
|
private function processContentFiles(array $content): array
|
|
{
|
|
return collect($content)
|
|
->map(function ($value, $key) {
|
|
// Check the pattern of the key and the type of value.
|
|
if (
|
|
(
|
|
Str::startsWith($key, DynamicFieldTypes::image->name . '_')
|
|
|| Str::startsWith($key, DynamicFieldTypes::file->name . '_')
|
|
) && $value instanceof UploadedFile
|
|
) {
|
|
return FileHelper::storeFile($this, $value);
|
|
}
|
|
|
|
// Check if it's an array.
|
|
if (is_array($value)) {
|
|
return $this->processContentFiles($value);
|
|
}
|
|
|
|
return $value;
|
|
})
|
|
->all();
|
|
}
|
|
|
|
/**
|
|
* Unpublished all children pages if change status published from draft/unpublished.
|
|
*
|
|
* @param self $model
|
|
* @return boolean
|
|
*/
|
|
private static function setAllChildPageStatus(self $model): void
|
|
{
|
|
if (
|
|
!$model->status->equals(PageStatusEnum::published)
|
|
&& !$model->getOriginal('status')->equals($model->status)
|
|
) {
|
|
$model->childPages->map(function (DynamicPage $page) use ($model) {
|
|
$page->status = $model->status;
|
|
$page->saveOrFail();
|
|
});
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Publish current page if all parents are published.
|
|
*
|
|
* @param self $model
|
|
* @return boolean
|
|
* @throws \Illuminate\Validation\ValidationException Parent must be published.
|
|
*/
|
|
private static function checkParentsStatus(self $model): void
|
|
{
|
|
if ($model->status->equals(PageStatusEnum::published) && !self::getParentsStatus($model)) {
|
|
throw ValidationException::withMessages([
|
|
'error' => trans('validation.parent_page'),
|
|
]);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Check if all parent of all associated page are published.
|
|
*
|
|
* @param self $model
|
|
* @return boolean
|
|
*/
|
|
private static function getParentsStatus(self $model): bool
|
|
{
|
|
$parent = $model->parentPage;
|
|
while ($parent) {
|
|
if (!$parent->status->equals(PageStatusEnum::published)) {
|
|
return false;
|
|
}
|
|
$parent = $parent->parentPage;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* Manage model fields.
|
|
*
|
|
* @param self $model
|
|
* @return void
|
|
*/
|
|
private static function manageFields(self $model): void
|
|
{
|
|
// Check unique fields.
|
|
if($model->isRoot) {
|
|
self::assertRootIsUnique($model);
|
|
} else {
|
|
$slug = $model->slug ?? Str::slug($model->title);
|
|
TranslationHelper::assertTranslationFieldIsUnique($model, $model->title, 'title');
|
|
TranslationHelper::assertTranslationFieldIsUnique($model, $slug, 'slug');
|
|
$model->setAttribute('slug', $slug);
|
|
}
|
|
// Check translations.
|
|
self::validateFallbackTranslations($model);
|
|
}
|
|
|
|
/**
|
|
* Assert there is only one root page.
|
|
*
|
|
* @param self $model
|
|
* @return void
|
|
*/
|
|
public static function assertRootIsUnique(self $model): void
|
|
{
|
|
$oldDynamicPageRoot = self::getModelsCached()->where('isRoot', true)->first();
|
|
if ($oldDynamicPageRoot) {
|
|
$oldDynamicPageRoot->isRoot = false;
|
|
$oldDynamicPageRoot->saveQuietly();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 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(PageStatusEnum::published)) {
|
|
return;
|
|
}
|
|
TranslationHelper::validateFallbackTranslations($model);
|
|
}
|
|
|
|
/**
|
|
* Get the view of a specific dynamic page.
|
|
*
|
|
* @return string
|
|
*/
|
|
public function getView(): string
|
|
{
|
|
/** @var string $view The view used for the route. */
|
|
$view = PageConfig::$defaultView;
|
|
|
|
// Check if the view in config is defined and can be used.
|
|
if (!empty($this->config->view)) {
|
|
$candidate = sprintf('front.pages.%s', $this->config->view);
|
|
if (view()->exists($candidate)) {
|
|
$view = $candidate;
|
|
}
|
|
}
|
|
|
|
// Check if a view with the slug exists.
|
|
if ($view === PageConfig::$defaultView && !empty($this->slug)) {
|
|
$candidate = sprintf('front.pages.%s', $this->slug);
|
|
if (view()->exists($candidate)) {
|
|
$view = $candidate;
|
|
}
|
|
}
|
|
return $view;
|
|
}
|
|
|
|
/**
|
|
* Get the url to access a specific resource.
|
|
*
|
|
* @param integer $id Id field of the target model.
|
|
* @return string
|
|
*/
|
|
public static function getAccessModel(int $id): string
|
|
{
|
|
$targetModel = self::getModelsCached()->firstWhere('id', $id);
|
|
if (!$targetModel) {
|
|
return null;
|
|
}
|
|
$url = RouteHelper::routeNameChecker("front.dynamic-pages.{$targetModel->id_key}");
|
|
return parse_url($url, PHP_URL_PATH);
|
|
}
|
|
|
|
// * RELATIONSHIPS
|
|
|
|
/**
|
|
* Get children pages for this page.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\DynamicPage,$this>
|
|
*/
|
|
public function childPages(): \Illuminate\Database\Eloquent\Relations\HasMany
|
|
{
|
|
return $this->hasMany(DynamicPage::class, 'page_id');
|
|
}
|
|
|
|
/**
|
|
* Get parent page for this page.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\DynamicPage,$this>
|
|
*/
|
|
public function parentPage(): \Illuminate\Database\Eloquent\Relations\BelongsTo
|
|
{
|
|
return $this->belongsTo(DynamicPage::class, 'page_id');
|
|
}
|
|
|
|
/**
|
|
* Get the config for this page.
|
|
*
|
|
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo<\App\Models\PageConfig,$this>
|
|
*/
|
|
public function config(): \Illuminate\Database\Eloquent\Relations\BelongsTo
|
|
{
|
|
return $this->belongsTo(PageConfig::class, 'config_id');
|
|
}
|
|
|
|
/**
|
|
* Get localized path from the locale
|
|
*
|
|
* @param string $locale
|
|
* @return string|null
|
|
*/
|
|
public function getLocalizedPath(string $locale): ?string
|
|
{
|
|
$slug = $this->getTranslation('slug', $locale);
|
|
|
|
if (! $slug) {
|
|
return null;
|
|
}
|
|
|
|
// Récupère toutes les pages publiées (cache déjà existant chez toi)
|
|
$pages = static::getModelsCached()
|
|
->where('status', PageStatusEnum::published)
|
|
->load('parentPage')
|
|
->keyBy('id');
|
|
|
|
$segments = DynamicPageHelper::getAllDynamicPageSegments($this, $pages, $locale);
|
|
|
|
$segmentsPath = implode('/', $segments);
|
|
|
|
return $segmentsPath
|
|
? "{$segmentsPath}/{$slug}"
|
|
: $slug;
|
|
}
|
|
|
|
}
|