|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Spiral\Stempler\Directive; |
|
6
|
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
|
8
|
|
|
use Spiral\Core\Attribute\Singleton; |
|
9
|
|
|
use Spiral\Router\Exception\RouterException; |
|
10
|
|
|
use Spiral\Router\Exception\UndefinedRouteException; |
|
11
|
|
|
use Spiral\Router\RouterInterface; |
|
12
|
|
|
use Spiral\Stempler\Exception\DirectiveException; |
|
13
|
|
|
use Spiral\Stempler\Node\Dynamic\Directive; |
|
14
|
|
|
|
|
15
|
|
|
#[Singleton] |
|
16
|
|
|
final class RouteDirective extends AbstractDirective |
|
17
|
|
|
{ |
|
18
|
28 |
|
public function __construct( |
|
19
|
|
|
private readonly ContainerInterface $container, |
|
20
|
|
|
) { |
|
21
|
28 |
|
parent::__construct(); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Injects service into template. |
|
26
|
|
|
*/ |
|
27
|
1 |
|
public function renderRoute(Directive $directive): string |
|
28
|
|
|
{ |
|
29
|
1 |
|
if (\count($directive->values) < 1) { |
|
30
|
|
|
throw new DirectiveException( |
|
31
|
|
|
'Unable to call @route directive, at least 1 value is required', |
|
32
|
|
|
$directive->getContext(), |
|
|
|
|
|
|
33
|
|
|
); |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
1 |
|
return \sprintf( |
|
37
|
1 |
|
'<?php echo $this->container->get(\Spiral\Stempler\Directive\RouteDirective::class)->uri(%s); ?>', |
|
38
|
1 |
|
$directive->body, |
|
39
|
1 |
|
); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Provides the ability to inject templated args in a form or {id} or {{id}}. |
|
44
|
|
|
*/ |
|
45
|
|
|
public function uri(string $route, array $params = []): string |
|
46
|
|
|
{ |
|
47
|
|
|
$vars = []; |
|
48
|
|
|
$restore = []; |
|
49
|
|
|
foreach ($params as $key => $value) { |
|
50
|
|
|
if (\is_string($value) && \preg_match('#\{.*\}#', $value)) { |
|
51
|
|
|
$restore[\sprintf('__%s__', $key)] = $value; |
|
52
|
|
|
$value = \sprintf('__%s__', $key); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$vars[$key] = $value; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
try { |
|
59
|
|
|
return \strtr( |
|
60
|
|
|
$this->container->get(RouterInterface::class)->uri($route, $vars)->__toString(), |
|
61
|
|
|
$restore, |
|
62
|
|
|
); |
|
63
|
|
|
} catch (UndefinedRouteException $e) { |
|
64
|
|
|
throw new RouterException("No such route {$route}", $e->getCode(), $e); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|