-
-
Notifications
You must be signed in to change notification settings - Fork 513
/
LoadsTranslatedCachedRoutes.php
95 lines (78 loc) · 2.46 KB
/
LoadsTranslatedCachedRoutes.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
namespace Mcamara\LaravelLocalization\Traits;
use Illuminate\Support\Facades\Log;
/**
* LoadsTranslatedCachedRoutes
*
* Add this trait to your App\RouteServiceProvider to load
* translated cached routes for the active locale, instead
* of the default locale's routes (irrespective of active).
*/
trait LoadsTranslatedCachedRoutes
{
/**
* Load the cached routes for the application.
*
* @return void
*/
protected function loadCachedRoutes()
{
$localization = $this->getLaravelLocalization();
// compute $locale from url.
// It is null if url does not contain locale.
$locale = $localization->getInversedLocaleFromMapping(
$localization->setLocale()
);
$localeKeys = $localization->getSupportedLanguagesKeys();
// First, try to load the routes specifically cached for this locale
// if they do not exist, write a warning to the log and load the default
// routes instead. Note that this is guaranteed to exist, because the
// 'cached routes' check in the Application checks its existence.
$path = $this->makeLocaleRoutesPath($locale, $localeKeys);
if ( ! file_exists($path)) {
Log::warning("Routes cached, but no cached routes found for locale '{$locale}'!");
$path = $this->getDefaultCachedRoutePath();
}
$this->app->booted(function () use ($path) {
require $path;
});
}
/**
* Returns the path to the cached routes file for a given locale.
*
* @param string $locale
* @param string[] $localeKeys
* @return string
*/
protected function makeLocaleRoutesPath($locale, $localeKeys)
{
$path = $this->getDefaultCachedRoutePath();
if ( ! $locale || ! in_array($locale, $localeKeys)) {
return $path;
}
return substr($path, 0, -4) . '_' . $locale . '.php';
}
/**
* Returns the path to the standard cached routes file.
*
* @return string
*/
protected function getDefaultCachedRoutePath()
{
return $this->app->getCachedRoutesPath();
}
/**
* @return string|null
*/
protected function getLocaleFromRequest()
{
return request()->segment(1);
}
/**
* @return \Mcamara\LaravelLocalization\LaravelLocalization
*/
protected function getLaravelLocalization()
{
return app('laravellocalization');
}
}