Skip to content

Commit

Permalink
Add locale middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
akalongman committed Apr 17, 2024
1 parent 5618f24 commit 780230a
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/Lodash/Middlewares/ApiLocale.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace Longman\LaravelLodash\Middlewares;

use Closure;
use Illuminate\Http\Request;

use function app;
use function array_keys;
use function config;
use function setlocale;

use const LC_ALL;

class ApiLocale
{
public function handle(Request $request, Closure $next)
{
if ($request->wantsJson()) {
$locales = config('lodash.locales', []);
$locale = $request->getPreferredLanguage(array_keys($locales));
app()->setLocale($locale);
}

/** @var \Symfony\Component\HttpFoundation\Response $response */
$response = $next($request);
$locale = app()->getLocale();
$response->headers->set('Content-Language', $locale, true);

if (! empty($locales[$locale])) {
setlocale(LC_ALL, $locales[$locale]['full_locale']);
}

return $response;
}
}
19 changes: 19 additions & 0 deletions src/config/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,25 @@
declare(strict_types=1);

return [
'locales' => [
'en' => [
'name' => 'English',
'native_name' => 'English',
'flag' => 'gb',
'locale' => 'en',
'canonical_locale' => 'en_GB',
'full_locale' => 'en_GB.UTF-8',
],
'ka' => [
'name' => 'Georgian',
'native_name' => 'ქართული',
'flag' => 'ge',
'locale' => 'ka',
'canonical_locale' => 'ka_GE',
'full_locale' => 'ka_GE.UTF-8',
],
],

'debug' => [
'ips' => explode(',', env('DEBUG_IP_LIST', '')), // IP list for enabling debug mode
],
Expand Down

0 comments on commit 780230a

Please sign in to comment.