|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Acelaya\Website\Service; |
|
5
|
|
|
|
|
6
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
7
|
|
|
use Zend\Expressive\Router\RouteResult; |
|
8
|
|
|
use Zend\Expressive\Router\RouterInterface; |
|
9
|
|
|
|
|
10
|
|
|
class RouteAssembler implements RouteAssemblerInterface |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var RouterInterface |
|
14
|
|
|
*/ |
|
15
|
|
|
protected $router; |
|
16
|
|
|
/** |
|
17
|
|
|
* @var ServerRequestInterface |
|
18
|
|
|
*/ |
|
19
|
|
|
protected $request; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(RouterInterface $router, ServerRequestInterface $request) |
|
22
|
|
|
{ |
|
23
|
|
|
$this->router = $router; |
|
24
|
|
|
$this->request = $request; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
5 |
|
/** |
|
28
|
|
|
* Assembles a route with given name using given information |
|
29
|
5 |
|
* |
|
30
|
5 |
|
* @param string|null $name |
|
31
|
5 |
|
* @param array|bool $routeParams |
|
32
|
|
|
* @param array|bool $queryParams |
|
33
|
|
|
* @param bool $inherit Tells if route and query params should be inherited from current route |
|
34
|
|
|
* @return string |
|
35
|
|
|
*/ |
|
36
|
|
|
public function assembleUrl( |
|
37
|
|
|
string $name = null, |
|
38
|
|
|
$routeParams = [], |
|
39
|
|
|
$queryParams = [], |
|
40
|
|
|
bool $inherit = false |
|
41
|
|
|
): string { |
|
42
|
5 |
|
$routeResult = $this->getCurrentRouteResult(); |
|
43
|
|
|
if ($name === null) { |
|
44
|
|
|
$name = $routeResult->isSuccess() ? $routeResult->getMatchedRouteName() : 'home'; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
if (is_bool($routeParams)) { |
|
48
|
5 |
|
$inherit = $routeParams; |
|
49
|
5 |
|
$routeParams = []; |
|
50
|
|
|
} |
|
51
|
5 |
|
|
|
52
|
1 |
|
if (is_bool($queryParams)) { |
|
53
|
1 |
|
$inherit = $queryParams; |
|
54
|
|
|
$queryParams = []; |
|
55
|
|
|
} |
|
56
|
5 |
|
|
|
57
|
1 |
|
if ($inherit) { |
|
58
|
1 |
|
$routeParams = array_merge($routeResult->getMatchedParams(), $routeParams); |
|
59
|
|
|
$queryParams = array_merge($this->request->getQueryParams(), $queryParams); |
|
60
|
|
|
} |
|
61
|
5 |
|
|
|
62
|
2 |
|
$queryString = empty($queryParams) ? '' : sprintf('?%s', http_build_query($queryParams)); |
|
63
|
2 |
|
return $this->router->generateUri($name, $routeParams) . $queryString; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
5 |
|
/** |
|
67
|
5 |
|
* @return RouteResult |
|
68
|
|
|
*/ |
|
69
|
|
|
public function getCurrentRouteResult(): RouteResult |
|
70
|
|
|
{ |
|
71
|
|
|
return $this->router->match($this->request); |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|