61 lines
2.2 KiB
PHP
61 lines
2.2 KiB
PHP
<?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);
|
|
}
|
|
}
|
|
}
|