1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Faulancer\View\Helper; |
4
|
|
|
|
5
|
|
|
use Faulancer\Exception\RouteInvalidException; |
6
|
|
|
use Faulancer\Exception\ServiceNotFoundException; |
7
|
|
|
use Faulancer\Http\Request; |
8
|
|
|
use Faulancer\Service\Config; |
9
|
|
|
use Faulancer\Service\RequestService; |
10
|
|
|
use Faulancer\ServiceLocator\ServiceLocator; |
11
|
|
|
use Faulancer\View\AbstractViewHelper; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class Route | Route.php |
15
|
|
|
* @package Faulancer\View\Helper |
16
|
|
|
* @author Florian Knapp <[email protected]> |
17
|
|
|
*/ |
18
|
|
|
class Route extends AbstractViewHelper |
19
|
|
|
{ |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Get route path by name |
23
|
|
|
* |
24
|
|
|
* @param string $name |
25
|
|
|
* @param array $parameters |
26
|
|
|
* @param bool $absolute |
27
|
|
|
* |
28
|
|
|
* @return string |
29
|
|
|
* |
30
|
|
|
* @throws RouteInvalidException |
31
|
|
|
* @throws ServiceNotFoundException |
32
|
|
|
*/ |
33
|
|
|
public function __invoke(string $name, array $parameters = [], $absolute = false) |
34
|
|
|
{ |
35
|
|
|
/** @var Config $config */ |
36
|
|
|
$config = ServiceLocator::instance()->get(Config::class); |
37
|
|
|
$routes = $config->get('routes'); |
38
|
|
|
|
39
|
|
|
$apiRoutes = $config->get('routes:rest') ?? []; |
40
|
|
|
|
41
|
|
|
$routes = array_merge($routes, $apiRoutes); |
42
|
|
|
$path = ''; |
43
|
|
|
|
44
|
|
|
foreach ($routes as $routeName => $data) { |
45
|
|
|
|
46
|
|
|
if ($routeName === $name) { |
47
|
|
|
$path = preg_replace('|/\((.*)\)|', '', $data['path']); |
48
|
|
|
break; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
if (empty($path)) { |
54
|
|
|
throw new RouteInvalidException('No route for name "' . $name . '" found'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
if (!empty($parameters)) { |
58
|
|
|
|
59
|
|
|
if (in_array('query', array_keys($parameters), true)) { |
60
|
|
|
$query = $parameters['query']; |
61
|
|
|
$query = http_build_query($query); |
62
|
|
|
$path = $path . '?' . $query; |
63
|
|
|
} else { |
64
|
|
|
$path = $path . '/' . implode('/', $parameters); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
$path = str_replace('//' , '/', $path); |
70
|
|
|
|
71
|
|
|
if ($absolute) { |
72
|
|
|
|
73
|
|
|
/** @var Request $request */ |
74
|
|
|
$request = $this->getServiceLocator()->get(RequestService::class); |
75
|
|
|
|
76
|
|
|
$path = $request->getScheme() |
77
|
|
|
. $request->getHost() |
78
|
|
|
. $path; |
79
|
|
|
|
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return $path; |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
} |