ldc-groupe/app/Models/PageConfig.php
2025-10-17 14:52:51 +02:00

128 lines
3.6 KiB
PHP

<?php
namespace App\Models;
use App\Enums\DynamicPages\PageStatusEnum;
use App\Traits\Models\HasTranslations;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* @property string $label Label of the page configuration.
* @property string|null $view View of the page configuration.
* @property array $config Config of the page.
* @property-read \Illuminate\Support\Carbon $created_at Date on which the page configuration was created.
* @property-read \Illuminate\Support\Carbon $updated_at Date on which the page configuration was updated.
* @property-read \Illuminate\Support\Carbon $deleted_at Date on which the page configuration was updated.
*/
class PageConfig extends Model
{
use HasFactory;
use HasTranslations;
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var list<string>
*/
protected $fillable = [
'label',
'view',
'config',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'config' => 'array',
];
/**
* The translatable columns.
*
* @var list<string>
*/
public $translatable = [
'label',
'config',
];
/**
* Perform any actions required after the model boots.
*
* @return void
*/
protected static function booted(): void
{
static::updated(function (self $model) {
/**
* If the config is updated, delete the content of all associated dynamic pages
* because of potentials breaking errors and set the status to draft.
*/
$oldConfig = $model->getOriginal('config');
if (isset($oldConfig[config('app.locale')])) {
$oldConfig = $oldConfig[config('app.locale')];
if (!self::isConfigUpdated($model->config, $oldConfig)) {
$model->pages->map(function (DynamicPage $dynamicPageModel) {
$dynamicPageModel->content = "";
$dynamicPageModel->status = PageStatusEnum::draft;
$dynamicPageModel->saveOrFail();
});
}
}
});
static::deleting(function (self $model) {
$model->pages()->delete();
});
static::restoring(function (self $model) {
$model->pages()->withTrashed()->restore();
});
}
/**
* Check if the config is updated.
*
* @param array $newArray
* @param array $originalArray
* @return boolean
*/
private static function isConfigUpdated(array $newArray, array $originalArray): bool
{
if (count($newArray) !== count($originalArray)) {
return false;
}
foreach ($newArray as $i => $subA) {
$subB = $originalArray[$i] ?? null;
if ($subB === null) {
return false;
}
ksort($subA);
ksort($subB);
if ($subA != $subB) {
return false;
}
}
return true;
}
// * RELATIONSHIPS
/**
* Get pages for the config.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany<\App\Models\DynamicPage,$this>
*/
public function pages(): \Illuminate\Database\Eloquent\Relations\HasMany
{
return $this->hasMany(DynamicPage::class, 'config_id');
}
}