RouteDirective::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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(),
0 ignored issues
show
Bug introduced by
It seems like $directive->getContext() can also be of type null; however, parameter $context of Spiral\Stempler\Exceptio...xception::__construct() does only seem to accept Spiral\Stempler\Parser\Context, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

32
                /** @scrutinizer ignore-type */ $directive->getContext(),
Loading history...
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