|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace BoneMvc\Module\I18n; |
|
4
|
|
|
|
|
5
|
|
|
use Locale; |
|
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
7
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
8
|
|
|
use Psr\Http\Server\MiddlewareInterface; |
|
9
|
|
|
use Psr\Http\Server\RequestHandlerInterface; |
|
10
|
|
|
use Zend\Expressive\Helper\UrlHelper; |
|
11
|
|
|
|
|
12
|
|
|
class InternationalisationMiddleware implements MiddlewareInterface |
|
13
|
|
|
{ |
|
14
|
|
|
/** @var UrlHelper */ |
|
15
|
|
|
private $helper; |
|
16
|
|
|
|
|
17
|
|
|
/** @var string|null */ |
|
18
|
|
|
private $defaultLocale; |
|
19
|
|
|
|
|
20
|
|
|
/** @var string $fallbackLocale */ |
|
21
|
|
|
private $fallbackLocale = 'en_US'; |
|
22
|
|
|
|
|
23
|
|
|
const REGEX_LOCALE = '#^/(?P<locale>[a-z]{2,3}|[a-z]{2}[-_][a-zA-Z]{2})(?:/|$)#'; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* InternationalisationMiddleware constructor. |
|
27
|
|
|
* @param $helper |
|
28
|
|
|
* @param string|null $defaultLocale |
|
29
|
|
|
*/ |
|
30
|
|
|
public function __construct( $helper, string $defaultLocale = null) |
|
31
|
|
|
{ |
|
32
|
|
|
$this->helper = $helper; |
|
33
|
|
|
if ($defaultLocale) { |
|
|
|
|
|
|
34
|
|
|
$this->defaultLocale = $defaultLocale; |
|
35
|
|
|
} |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param ServerRequestInterface $request |
|
40
|
|
|
* @param RequestHandlerInterface $handler |
|
41
|
|
|
* @return ResponseInterface |
|
42
|
|
|
*/ |
|
43
|
|
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface |
|
44
|
|
|
{ |
|
45
|
|
|
$uri = $request->getUri(); |
|
46
|
|
|
die('aye ' . $uri); |
|
47
|
|
|
$path = $uri->getPath(); |
|
|
|
|
|
|
48
|
|
|
|
|
49
|
|
|
if (! preg_match(self::REGEX_LOCALE, $path, $matches)) { |
|
50
|
|
|
Locale::setDefault($this->defaultLocale ?: $this->fallbackLocale); |
|
51
|
|
|
return $handler->handle($request); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
$locale = $matches['locale']; |
|
55
|
|
|
Locale::setDefault(Locale::canonicalize($locale)); |
|
56
|
|
|
$this->helper->setBasePath($locale); |
|
57
|
|
|
|
|
58
|
|
|
$path = substr($path, strlen($locale) + 1); |
|
59
|
|
|
|
|
60
|
|
|
return $handler->handle($request->withUri( |
|
61
|
|
|
$uri->withPath($path ?: '/') |
|
62
|
|
|
)); |
|
63
|
|
|
} |
|
64
|
|
|
} |
In PHP, under loose comparison (like
==, or!=, orswitchconditions), values of different types might be equal.For
stringvalues, the empty string''is a special case, in particular the following results might be unexpected: