1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Fomvasss\UrlAliases; |
4
|
|
|
|
5
|
|
|
use Fomvasss\UrlAliases\Traits\Localization; |
6
|
|
|
|
7
|
|
|
class UrlAliasLocalization |
8
|
|
|
{ |
9
|
|
|
use Localization; |
10
|
|
|
|
11
|
|
|
protected $app; |
12
|
|
|
|
13
|
|
|
protected $config; |
14
|
|
|
|
15
|
|
|
protected $defaultLocale; |
16
|
|
|
|
17
|
|
|
protected $supportedLocales; |
18
|
|
|
|
19
|
|
|
protected $currentLocale; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Localization constructor. |
23
|
|
|
* @param $app |
24
|
|
|
*/ |
25
|
|
|
public function __construct($app) |
26
|
|
|
{ |
27
|
|
|
if (!$app) { |
28
|
|
|
$app = app(); //Fallback when $app is not given |
|
|
|
|
29
|
|
|
} |
30
|
|
|
$this->app = $app; |
31
|
|
|
|
32
|
|
|
$this->config = $this->app['config']; |
33
|
|
|
|
34
|
|
|
$this->defaultLocale = $this->getDefaultLocale(); |
35
|
|
|
|
36
|
|
|
$this->currentLocale = $this->defaultLocale; |
37
|
|
|
|
38
|
|
|
$this->supportedLocales = $this->getSupportedLocales(); |
39
|
|
|
|
40
|
|
|
if (empty($this->supportedLocales[$this->defaultLocale])) { |
41
|
|
|
throw new \Exception('Laravel default locale is not in the supportedLocales array.'); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* TODO: remove $segment1 |
47
|
|
|
* @param $path |
48
|
|
|
* @param $segment1 |
49
|
|
|
* @return \Illuminate\Http\RedirectResponse|string |
|
|
|
|
50
|
|
|
*/ |
51
|
|
|
public function prepareLocalizePath(string $path): array |
52
|
|
|
{ |
53
|
|
|
// session()->put('locale', $this->defaultLocale); |
54
|
|
|
$segment1 = url_path_segments($path, 1); |
55
|
|
|
|
56
|
|
|
if (key_exists($segment1, $this->supportedLocales)) { |
57
|
|
|
// session()->put('locale', $segment1); |
58
|
|
|
|
59
|
|
|
$path = preg_replace("/^$segment1\\//", "", "$path"); |
60
|
|
|
|
61
|
|
|
if ($this->hideDefaultLocaleInURL() && $segment1 === $this->defaultLocale) { |
62
|
|
|
$path = ($path == $segment1) ? '/' : $path; |
63
|
|
|
return ['redirect' => $path]; |
|
|
|
|
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
$this->currentLocale = $segment1; |
67
|
|
|
$this->app->setLocale($segment1); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
// Regional locale such as de_DE, so formatLocalized works in Carbon |
71
|
|
|
$regional = $this->getCurrentLocaleRegional(); |
72
|
|
|
$suffix = $this->config->get('url-aliases.laravellocalization.utf8suffix'); |
73
|
|
|
if ($regional) { |
74
|
|
|
setlocale(LC_TIME, $regional . $suffix); |
75
|
|
|
setlocale(LC_MONETARY, $regional . $suffix); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return ['path' => $path]; |
|
|
|
|
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @return bool |
83
|
|
|
*/ |
84
|
|
|
protected function hideDefaultLocaleInURL() |
85
|
|
|
{ |
86
|
|
|
return $this->config->get('url-aliases-laravellocalization.hideDefaultLocaleInURL'); |
87
|
|
|
} |
88
|
|
|
} |