1 | <?php |
||
14 | final class Detect |
||
15 | { |
||
16 | /** |
||
17 | * @var Request |
||
18 | */ |
||
19 | private $request; |
||
20 | |||
21 | /** |
||
22 | * @var Config |
||
23 | */ |
||
24 | private $config; |
||
25 | |||
26 | /** |
||
27 | * @var Locale |
||
28 | */ |
||
29 | private $locale; |
||
30 | |||
31 | /** |
||
32 | * Current scope of locales. |
||
33 | * |
||
34 | * @var Scope |
||
35 | */ |
||
36 | private $scope; |
||
37 | |||
38 | public function __construct(Request $request, Config $config) |
||
|
|||
39 | { |
||
40 | $this->request = $request; |
||
41 | $this->config = $config; |
||
42 | } |
||
43 | |||
44 | /** |
||
45 | * Detect the locale from current request url. |
||
46 | * Once the locale has been determined, it will be set as the application locale. |
||
47 | * A locale is only validated if it is present within the current locale scope. |
||
48 | * |
||
49 | * Detection honours following priority: |
||
50 | * 1) If locale is found in request as query parameter e.g. ?locale=fr, |
||
51 | * 2) If locale is found in request url, either from host or segment eg. nl.example.com, example.nl or example.com/nl |
||
52 | * 3) Otherwise set locale to our fallback language (app.locale) |
||
53 | */ |
||
54 | public function detectLocale(): self |
||
55 | { |
||
56 | $locale = null; |
||
57 | |||
58 | $detectors = [ |
||
59 | FallbackDetector::class, |
||
60 | HiddenSegmentDetector::class, |
||
61 | SegmentDetector::class, |
||
62 | QueryDetector::class, |
||
63 | ]; |
||
64 | |||
65 | foreach ($detectors as $detector) { |
||
66 | $locale = app($detector)->get($this->getScope(), $this->config) ?? $locale; |
||
67 | } |
||
68 | |||
69 | $this->locale = $locale; |
||
70 | |||
71 | Scope::setActiveLocale($locale); |
||
72 | |||
73 | $this->setApplicationLocale(); |
||
74 | |||
75 | return $this; |
||
76 | } |
||
77 | |||
78 | public function getLocale(): Locale |
||
79 | { |
||
80 | if (!$this->locale) { |
||
81 | $this->detectLocale(); |
||
82 | } |
||
83 | |||
84 | return $this->locale; |
||
85 | } |
||
86 | |||
87 | public function getScope(): Scope |
||
88 | { |
||
89 | if (!$this->scope) { |
||
90 | $this->detectScope(); |
||
91 | } |
||
92 | |||
93 | return $this->scope; |
||
94 | } |
||
95 | |||
96 | public function getConfig(): Config |
||
100 | |||
101 | /** |
||
102 | * This is handy for setting allowed scope via other source than config file. |
||
103 | * this can be configurable from a cms. |
||
104 | * |
||
105 | * @param Scope|null $scope |
||
106 | * |
||
107 | * @return $this |
||
108 | */ |
||
109 | public function setScope(Scope $scope = null) |
||
117 | |||
118 | private function detectScope() |
||
122 | |||
123 | private function setApplicationLocale() |
||
129 | } |
||
130 |