From 431862b35c4a31f7209844118ead74b1e4aa97a5 Mon Sep 17 00:00:00 2001 From: Phil Bates Date: Thu, 18 Jan 2024 13:47:21 +0000 Subject: [PATCH] Translation: Log a warning for any unknown lang keys Based on https://laravel.com/docs/10.x/localization#handling-missing-translation-strings. Use "resolving" callback instead of using the Log facade / the 'log' service because if we do that it will force the deferred LogServiceProvider to be registered on every request, essentially making it not deferred any more. Similar to how Model::shouldBeStrict() is only called when not in production, we only throw an exception when not in production. --- app/Providers/AppServiceProvider.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index ef86559..2db790e 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -5,7 +5,10 @@ namespace App\Providers; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Facades\Log; use Illuminate\Support\ServiceProvider; +use Illuminate\Translation\Translator; +use OutOfBoundsException; class AppServiceProvider extends ServiceProvider { @@ -14,7 +17,19 @@ class AppServiceProvider extends ServiceProvider */ public function register(): void { - // + $this->app->resolving('translator', static function (Translator $translator): void { + $translator->handleMissingKeysUsing(static function (string $key): string { + $message = "Missing translation key [{$key}] detected."; + + if (!$this->isProduction()) { + throw new OutOfBoundsException($message); + } + + Log::warning($message); + + return $key; + }); + }); } /**