1 | <?php |
||
2 | |||
3 | namespace Turahe\Master\Middleware; |
||
4 | |||
5 | use Closure; |
||
6 | use Illuminate\Http\Request; |
||
7 | |||
8 | class CurrencyMiddleware |
||
9 | { |
||
10 | /** |
||
11 | * Handle an incoming request. |
||
12 | * |
||
13 | * @param Request $request |
||
14 | * @param Closure $next |
||
15 | * |
||
16 | * @return mixed |
||
17 | */ |
||
18 | public function handle($request, Closure $next) |
||
19 | { |
||
20 | // Don't redirect the console |
||
21 | if ($this->runningInConsole()) { |
||
22 | return $next($request); |
||
23 | } |
||
24 | |||
25 | // Check for a user defined currency |
||
26 | if (($currency = $this->getUserCurrency($request)) === null) { |
||
27 | $currency = $this->getDefaultCurrency(); |
||
28 | } |
||
29 | |||
30 | // Set user currency |
||
31 | $this->setUserCurrency($currency, $request); |
||
32 | |||
33 | return $next($request); |
||
34 | } |
||
35 | |||
36 | /** |
||
37 | * Get the user selected currency. |
||
38 | * |
||
39 | * @param Request $request |
||
40 | * |
||
41 | * @return null|string |
||
42 | */ |
||
43 | protected function getUserCurrency(Request $request) |
||
44 | { |
||
45 | // Check request for currency |
||
46 | $currency = $request->get('currency'); |
||
47 | if ($currency && currency()->isActive($currency) === true) { |
||
48 | return $currency; |
||
49 | } |
||
50 | |||
51 | // Get currency from session |
||
52 | $currency = $request->getSession()->get('currency'); |
||
53 | if ($currency && currency()->isActive($currency) === true) { |
||
54 | return $currency; |
||
55 | } |
||
56 | |||
57 | return null; |
||
58 | } |
||
59 | |||
60 | /** |
||
61 | * Get the application default currency. |
||
62 | * |
||
63 | * @return string |
||
64 | */ |
||
65 | protected function getDefaultCurrency() |
||
66 | { |
||
67 | return currency()->config('default'); |
||
68 | } |
||
69 | |||
70 | /** |
||
71 | * Determine if the application is running in the console. |
||
72 | * |
||
73 | * @return bool |
||
74 | */ |
||
75 | private function runningInConsole() |
||
76 | { |
||
77 | return app()->runningInConsole(); |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
78 | } |
||
79 | |||
80 | /** |
||
81 | * Set the user currency. |
||
82 | * |
||
83 | * @param string $currency |
||
84 | * @param Request $request |
||
85 | * |
||
86 | * @return string |
||
87 | */ |
||
88 | private function setUserCurrency($currency, $request) |
||
89 | { |
||
90 | $currency = strtoupper($currency); |
||
91 | |||
92 | // Set user selection globally |
||
93 | currency()->setUserCurrency($currency); |
||
94 | |||
95 | // Save it for later too! |
||
96 | $request->getSession()->put(['currency' => $currency]); |
||
97 | |||
98 | return $currency; |
||
99 | } |
||
100 | } |
||
101 |