fix: 🐛 update validations of fields translation
This commit is contained in:
parent
270f0e3c29
commit
fb57db6a4c
13 changed files with 197 additions and 92 deletions
24
app/Contracts/TranslatableModel.php
Normal file
24
app/Contracts/TranslatableModel.php
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
<?php
|
||||
|
||||
namespace App\Contracts;
|
||||
|
||||
interface TranslatableModel
|
||||
{
|
||||
/**
|
||||
* Get all translatable attributes.
|
||||
*
|
||||
* @param string|null $key
|
||||
* @param array|null $allowedLocales
|
||||
* @return array
|
||||
*/
|
||||
public function getTranslations(?string $key = null, ?array $allowedLocales = null): array;
|
||||
|
||||
/**
|
||||
* Verefy that a specific attribute has locale.
|
||||
*
|
||||
* @param string $key
|
||||
* @param string|null $locale
|
||||
* @return boolean
|
||||
*/
|
||||
public function hasTranslation(string $key, ?string $locale = null): bool;
|
||||
}
|
||||
61
app/Helpers/TranslationHelper.php
Normal file
61
app/Helpers/TranslationHelper.php
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
<?php
|
||||
|
||||
namespace App\Helpers;
|
||||
|
||||
use App\Contracts\TranslatableModel;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class TranslationHelper
|
||||
{
|
||||
/**
|
||||
* Get all cached translations.
|
||||
*
|
||||
* @param string|null $locale
|
||||
* @return array
|
||||
*/
|
||||
public static function getCachedTranslations(?string $locale = null): array
|
||||
{
|
||||
if (is_null($locale)) {
|
||||
$locale = app()->getLocale();
|
||||
}
|
||||
return Cache::remember(sprintf('translations_%s', app()->getLocale()), 86400, function () {
|
||||
$translator = App::make('translator');
|
||||
$property = (new \ReflectionClass($translator))->getProperty('loaded');
|
||||
$property->setAccessible(true);
|
||||
return $property->getValue($translator);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert fallback locale translation is present.
|
||||
*
|
||||
* @param \App\Contracts\TranslatableModel $model
|
||||
* @return void
|
||||
* @throws \Illuminate\Validation\ValidationException Translations missing.
|
||||
*/
|
||||
public static function validateFallbackTranslations(TranslatableModel $model): void
|
||||
{
|
||||
$localeFallback = config('app.fallback_locale');
|
||||
$missingTranslations = [];
|
||||
foreach ($model->getTranslations() as $key => $value) {
|
||||
if (!is_null($model->{$key}) && !$model->hasTranslation($key, $localeFallback)) {
|
||||
$validationTranslations = self::getCachedTranslations()['validation'];
|
||||
$field = (array_key_exists($key, $validationTranslations['attributes']))
|
||||
? trans("validation.attributes.$key")
|
||||
: trans("validation.custom.$key");
|
||||
$missingTranslations = array_merge($missingTranslations, [
|
||||
$key => trans_choice('back.missing_translations', 1, [
|
||||
'field' => $field,
|
||||
'locales' => Str::upper($localeFallback),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
if ($missingTranslations) {
|
||||
throw ValidationException::withMessages($missingTranslations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -35,7 +35,7 @@ class DynamicPageController extends Controller
|
|||
$query = DynamicPage::query()->with('config');
|
||||
|
||||
if ($request->routeIs("back.dynamic-pages.trash")) {
|
||||
$query = $query->onlyTrashed();
|
||||
$query = $query->onlyTrashed()->with(['config' => fn($q) => $q->withTrashed()]);
|
||||
}
|
||||
|
||||
/** @var string $search Search field */
|
||||
|
|
@ -185,14 +185,14 @@ class DynamicPageController extends Controller
|
|||
/** @var array<string,string> */
|
||||
$previousQueries = [];
|
||||
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
|
||||
if ($dynamic_page->restoreQuietly()) {
|
||||
if ($dynamic_page->restore()) {
|
||||
return redirect()->route('back.dynamic-pages.trash', $previousQueries)
|
||||
->with('success', __('crud.messages.has_been_deleted', [
|
||||
->with('success', __('crud.messages.has_been_restored', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.dynamic-page', \INF))
|
||||
]));
|
||||
}
|
||||
return redirect()->back()
|
||||
->with('error', __('crud.messages.cannot_be_deleted', [
|
||||
->with('error', __('crud.messages.cannot_be_restored', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.dynamic-page', \INF))
|
||||
]));
|
||||
}
|
||||
|
|
@ -208,7 +208,7 @@ class DynamicPageController extends Controller
|
|||
/** @var array<string,string> */
|
||||
$previousQueries = [];
|
||||
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
|
||||
if ($dynamic_page->deleteQuietly()) {
|
||||
if ($dynamic_page->delete()) {
|
||||
return redirect()->route('back.dynamic-pages.index', $previousQueries)
|
||||
->with('success', __('crud.messages.has_been_deleted', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.dynamic-page', \INF))
|
||||
|
|
|
|||
|
|
@ -180,14 +180,14 @@ class PageConfigController extends Controller
|
|||
/** @var array<string,string> */
|
||||
$previousQueries = [];
|
||||
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
|
||||
if ($page_config->restoreQuietly()) {
|
||||
if ($page_config->restore()) {
|
||||
return redirect()->route('back.page-configs.trash', $previousQueries)
|
||||
->with('success', __('crud.messages.has_been_deleted', [
|
||||
->with('success', __('crud.messages.has_been_restored', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.page-config', \INF))
|
||||
]));
|
||||
}
|
||||
return redirect()->back()
|
||||
->with('error', __('crud.messages.cannot_be_deleted', [
|
||||
->with('error', __('crud.messages.cannot_be_restored', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.page-config', \INF))
|
||||
]));
|
||||
}
|
||||
|
|
@ -203,7 +203,7 @@ class PageConfigController extends Controller
|
|||
/** @var array<string,string> */
|
||||
$previousQueries = [];
|
||||
\parse_str(\parse_url(url()->previous(), \PHP_URL_QUERY), $previousQueries);
|
||||
if ($page_config->deleteQuietly()) {
|
||||
if ($page_config->delete()) {
|
||||
return redirect()->route('back.page-configs.index', $previousQueries)
|
||||
->with('success', __('crud.messages.has_been_deleted', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.page-config', \INF))
|
||||
|
|
|
|||
|
|
@ -4,12 +4,11 @@ namespace App\Http\Middleware;
|
|||
|
||||
use App\Enums\DynamicFieldTypes;
|
||||
use App\Enums\DynamicPages\PageStatusEnum;
|
||||
use App\Helpers\TranslationHelper;
|
||||
use App\Models\DynamicPage;
|
||||
use App\Models\PageConfig;
|
||||
use Diglactic\Breadcrumbs\Breadcrumbs;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\App;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Inertia\Middleware;
|
||||
use Uwil\LaravelBackend\Enums\RoleEnum;
|
||||
|
|
@ -34,12 +33,7 @@ class HandleInertiaRequests extends Middleware
|
|||
public function share(Request $request): array
|
||||
{
|
||||
// Get translations from translator app.
|
||||
$translations = Cache::remember(sprintf('translations_%s', app()->getLocale()), 86400, function () {
|
||||
$translator = App::make('translator');
|
||||
$property = (new \ReflectionClass($translator))->getProperty('loaded');
|
||||
$property->setAccessible(true);
|
||||
return $property->getValue($translator);
|
||||
});
|
||||
$translations = TranslationHelper::getCachedTranslations();
|
||||
|
||||
// Get all errors messages of session from middleware and redirect response.
|
||||
$errors = array_filter([
|
||||
|
|
|
|||
|
|
@ -2,8 +2,10 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Contracts\TranslatableModel;
|
||||
use App\Enums\DynamicFieldTypes;
|
||||
use App\Enums\DynamicPages\PageStatusEnum;
|
||||
use App\Helpers\TranslationHelper;
|
||||
use App\Traits\Models\HasTranslations;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
|
@ -25,7 +27,7 @@ use Uwil\LaravelCommon\Helpers\ToolboxHelper;
|
|||
* @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
|
||||
class DynamicPage extends Model implements TranslatableModel
|
||||
{
|
||||
use HasFactory;
|
||||
use HasTranslations;
|
||||
|
|
@ -75,20 +77,33 @@ class DynamicPage extends Model
|
|||
{
|
||||
static::creating(function (self $model) {
|
||||
self::manageFields($model);
|
||||
self::validateTranslations($model);
|
||||
self::validateFallbackTranslations($model);
|
||||
});
|
||||
static::created(function () {
|
||||
self::resetCache();
|
||||
});
|
||||
static::updating(function (self $model) {
|
||||
self::manageFields($model);
|
||||
self::validateTranslations($model);
|
||||
self::validateFallbackTranslations($model);
|
||||
});
|
||||
static::updated(function (self $model) {
|
||||
self::resetCache();
|
||||
self::removeImgs($model);
|
||||
});
|
||||
static::deleted(function (self $model) {
|
||||
static::deleted(function () {
|
||||
self::resetCache();
|
||||
});
|
||||
static::restoring(function (self $model) {
|
||||
if ($model->config_id && $model->config()->onlyTrashed()->exists()) {
|
||||
throw ValidationException::withMessages([
|
||||
'error' => __('crud.messages.cannot_be_restored', [
|
||||
'model' => Str::ucfirst(trans_choice('models.classes.dynamic-page', 1))
|
||||
]),
|
||||
]);
|
||||
}
|
||||
self::resetCache();
|
||||
});
|
||||
static::forceDeleted(function (self $model) {
|
||||
self::resetCache();
|
||||
self::removeImgs($model);
|
||||
});
|
||||
|
|
@ -110,40 +125,6 @@ class DynamicPage extends Model
|
|||
$model->slug = Str::slug($model->title);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate all translations required are defined.
|
||||
*
|
||||
* @param self $model
|
||||
* @return void
|
||||
* @throws \Illuminate\Validation\ValidationException Translations missing.
|
||||
*/
|
||||
public static function validateTranslations(self $model): void
|
||||
{
|
||||
if (! $model->status->equals(PageStatusEnum::published)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($model->config) {
|
||||
$modelLocales = collect(array_keys($model->config->getTranslations('config')));
|
||||
$locales = collect(config('app.locales'));
|
||||
$allowedLocales = $modelLocales->intersect($locales);
|
||||
|
||||
$missingLocales = $allowedLocales->reject(
|
||||
fn($locale) => $model->hasTranslation('content', $locale)
|
||||
);
|
||||
|
||||
if ($missingLocales->isNotEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'content' => trans_choice(
|
||||
'back.missing_translations',
|
||||
$missingLocales->count() > 2 ? \INF : 1,
|
||||
['locales' => Str::upper($missingLocales->implode(', '))]
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove imgs from wysiwyg OR dynamic wysiwyg.
|
||||
*
|
||||
|
|
@ -172,13 +153,30 @@ class DynamicPage extends Model
|
|||
});
|
||||
});
|
||||
} else {
|
||||
FileHelper::removeOldModelFilesFromHtml(
|
||||
$model->content,
|
||||
$model->getOriginal("content")[config('app.locale')]
|
||||
);
|
||||
if (isset($model->getOriginal("content")[config('app.locale')])) {
|
||||
FileHelper::removeOldModelFilesFromHtml(
|
||||
$model->content,
|
||||
$model->getOriginal("content")[config('app.locale')]
|
||||
);
|
||||
}
|
||||
} //end if
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset all cache elements related to this model.
|
||||
*
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@
|
|||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Contracts\TranslatableModel;
|
||||
use App\Enums\DynamicPages\PageStatusEnum;
|
||||
use App\Helpers\TranslationHelper;
|
||||
use App\Traits\Models\HasTranslations;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
|
@ -16,7 +18,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
|
|||
* @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
|
||||
class PageConfig extends Model implements TranslatableModel
|
||||
{
|
||||
use HasFactory;
|
||||
use HasTranslations;
|
||||
|
|
@ -59,6 +61,12 @@ class PageConfig extends Model
|
|||
*/
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (self $model) {
|
||||
TranslationHelper::validateFallbackTranslations($model);
|
||||
});
|
||||
static::updating(function (self $model) {
|
||||
TranslationHelper::validateFallbackTranslations($model);
|
||||
});
|
||||
static::updated(function (self $model) {
|
||||
/**
|
||||
* If the config is updated, delete the content of all associated dynamic pages
|
||||
|
|
@ -76,11 +84,20 @@ class PageConfig extends Model
|
|||
}
|
||||
}
|
||||
});
|
||||
static::deleting(function (self $model) {
|
||||
static::deleted(function (self $model) {
|
||||
$model->pages()->delete();
|
||||
});
|
||||
static::restoring(function (self $model) {
|
||||
$model->pages()->withTrashed()->restore();
|
||||
static::restored(function (self $model) {
|
||||
$model->pages()
|
||||
->onlyTrashed()
|
||||
->get()
|
||||
->map(function (DynamicPage $dynamicPageModel) {
|
||||
$dynamicPageModel->status = PageStatusEnum::draft;
|
||||
$dynamicPageModel->restore();
|
||||
});
|
||||
});
|
||||
static::forceDeleted(function (self $model) {
|
||||
$model->pages()->forceDelete();
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -88,6 +88,6 @@ return [
|
|||
"config_save_warning" => "The configuration of related pages in :locale will be updated accordingly.",
|
||||
"config_save_warning_list" => "Here is the list of :models concerned:|Here is the list of :models concerned:",
|
||||
"unsupported_type" => "Unsupported type:",
|
||||
"missing_translations" => "The translation for the language :locales is missing in order to publish this
|
||||
page.|Translations for :locales languages are missing in order to publish this page.",
|
||||
"missing_translations" => "The translation of the :field for the language :locales is missing.|The translation
|
||||
of the :field for :locales languages are missing.",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -50,6 +50,8 @@ return [
|
|||
"cannot_be_updated" => ":model cannot be updated",
|
||||
"has_been_deleted" => ":model has been deleted",
|
||||
"cannot_be_deleted" => ":model cannot be deleted",
|
||||
"has_been_restored" => ":model has been restored",
|
||||
"cannot_be_restored" => ":model cannot be restored",
|
||||
"order_changed" => "The order has been changed !",
|
||||
"order_not_changed" => "The order has not been changed !",
|
||||
"publish_status_saved" => "Successful change of publication status !",
|
||||
|
|
|
|||
|
|
@ -88,6 +88,6 @@ return [
|
|||
en conséquence.",
|
||||
"config_save_warning_list" => "Voici la liste des :models concernés:|Voici la liste des :models concernées:",
|
||||
"unsupported_type" => "Type non supporté:",
|
||||
"missing_translations" => "La traduction pour la langue :locales est manquante afin de publier cette page.|Les
|
||||
traductions pour les langues :locales sont manquantes afin de publier cette page.",
|
||||
"missing_translations" => "La traduction du champs :field pour la langue :locales est manquante.|La traduction
|
||||
du champs :field pour les langues :locales sont manquantes.",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -50,6 +50,8 @@ return [
|
|||
"cannot_be_updated" => ":model ne peut être mis à jour",
|
||||
"has_been_deleted" => ":model a été supprimé",
|
||||
"cannot_be_deleted" => ":model ne peut être supprimé",
|
||||
"has_been_restored" => ":model a été restoré",
|
||||
"cannot_be_restored" => ":model ne peut être restoré",
|
||||
"order_changed" => "L'ordre a été changé !",
|
||||
"order_not_changed" => "L'ordre n'a pas été changé !",
|
||||
"publish_status_saved" => "Changement de l'état de publication réussi !",
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout";
|
|||
import DataTable from "@/back/Components/Table/DataTable";
|
||||
import DataTableSearch from "@/back/Components/Table/DataTableSearch";
|
||||
import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton";
|
||||
import InputError from "@/back/Components/InputError";
|
||||
import BtnTooltip from "@/back/Components/BtnTooltip";
|
||||
import DynamicPageStatusBadge from "@/back/Components/DynamicPageStatusBadge";
|
||||
import { useFormatedDate } from "@/hooks/use-formated-value";
|
||||
|
|
@ -76,17 +77,16 @@ export default function Dashboard({
|
|||
),
|
||||
cell: ({ row }: { row: Row<DynamicPageModel> }) => {
|
||||
if (row.getValue("config")) {
|
||||
const cellValue = (row.getValue("config") as PageConfigModel).label[appEnv.locale];
|
||||
return auth.policies.pageConfigs.viewAny ? (
|
||||
const pageConfigModel = row.getValue("config") as PageConfigModel;
|
||||
const cellValue = pageConfigModel.label[appEnv.locale];
|
||||
return auth.policies.pageConfigs.viewAny && !pageConfigModel.deleted_at ? (
|
||||
<Button
|
||||
variant="secondary"
|
||||
type="button"
|
||||
size="sm"
|
||||
asChild
|
||||
>
|
||||
<Link
|
||||
href={route("back.page-configs.show", row.getValue("config"))}
|
||||
>
|
||||
<Link href={route("back.page-configs.show", row.getValue("config"))}>
|
||||
<Cog />
|
||||
<span>{cellValue}</span>
|
||||
</Link>
|
||||
|
|
@ -169,16 +169,19 @@ export default function Dashboard({
|
|||
afterNode={afterNode()}
|
||||
>
|
||||
{isArchiveRoute && (
|
||||
<Alert
|
||||
variant="destructive"
|
||||
className="text-left mb-4"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertTitle>{useTrans('back.warning')}</AlertTitle>
|
||||
<AlertDescription>
|
||||
<p>{useTrans('back.warning_trash')}</p>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<>
|
||||
<Alert
|
||||
variant="destructive"
|
||||
className="text-left mb-4"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertTitle>{useTrans('back.warning')}</AlertTitle>
|
||||
<AlertDescription>
|
||||
<p>{useTrans('back.warning_trash')}</p>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<InputError all={true} />
|
||||
</>
|
||||
)}
|
||||
<DataTableSearch
|
||||
modelRoute="dynamic-pages"
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import AuthenticatedLayout from "@/back/Layouts/AuthenticatedLayout";
|
|||
import DataTable from "@/back/Components/Table/DataTable";
|
||||
import DataTableSearch from "@/back/Components/Table/DataTableSearch";
|
||||
import DataTableFilterButton from "@/back/Components/Table/DataTableFilterButton";
|
||||
import InputError from "@/back/Components/InputError";
|
||||
import BtnTooltip from "@/back/Components/BtnTooltip";
|
||||
import { Views } from "@/lib/utils";
|
||||
import { useFormatedDate } from "@/hooks/use-formated-value";
|
||||
|
|
@ -133,16 +134,19 @@ export default function Dashboard({
|
|||
afterNode={afterNode()}
|
||||
>
|
||||
{isArchiveRoute && (
|
||||
<Alert
|
||||
variant="destructive"
|
||||
className="text-left mb-4"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertTitle>{useTrans('back.warning')}</AlertTitle>
|
||||
<AlertDescription>
|
||||
<p>{useTrans('back.warning_trash')}</p>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<>
|
||||
<Alert
|
||||
variant="destructive"
|
||||
className="text-left mb-4"
|
||||
>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertTitle>{useTrans('back.warning')}</AlertTitle>
|
||||
<AlertDescription>
|
||||
<p>{useTrans('back.warning_trash')}</p>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<InputError all={true} />
|
||||
</>
|
||||
)}
|
||||
<DataTableSearch
|
||||
modelRoute="page-configs"
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue