Issues (2)

src/Twig/Renderer.php (1 issue)

Labels
Severity
1
<?php
2
3
4
namespace Braunstetter\TemplateHooks\Twig;
5
6
use Traversable;
7
use Twig\Environment;
8
use Twig\Error\LoaderError;
9
use Twig\Error\RuntimeError;
10
use Twig\Error\SyntaxError;
11
12
class Renderer
13
{
14
    private iterable $hooks;
15
16
    public function __construct(iterable $hooks)
17
    {
18
        $this->hooks = $hooks;
19
    }
20
21
    /**
22
     * @param Environment $env
23
     * @param array $context
24
     * @param $name
25
     * @return string
26
     * @throws LoaderError
27
     * @throws RuntimeError
28
     * @throws SyntaxError
29
     */
30
    public function invokeHook(Environment $env, array $context, $name): string
31
    {
32
        $return = '';
33
34
        foreach ($this->hooks as $hook) {
35
36
            /** @var TemplateHook $hook */
37
            if ($this->targetMatches($hook, $name)) {
38
39
                $hook->setEnvironment($env);
40
                $hook->setContext($context);
41
42
                $return .= ' ';
43
                $return .= $hook->render();
44
            }
45
        }
46
47
        return $return;
48
    }
49
50
    /**
51
     * @param TemplateHook $hook
52
     * @param mixed $name
53
     * @return bool
54
     */
55
    private function targetMatches(TemplateHook $hook, mixed $name): bool
56
    {
57
        if (is_array($hook->target)) {
58
            return in_array($name, $hook->target);
59
        }
60
61
        return $hook->target === $name;
62
    }
63
64
    public function getMatchingHooks($name): iterable
65
    {
66
        return array_filter($this->hooks, function ($hook) use ($name) {
0 ignored issues
show
$this->hooks of type iterable is incompatible with the type array expected by parameter $array of array_filter(). ( Ignorable by Annotation )

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

66
        return array_filter(/** @scrutinizer ignore-type */ $this->hooks, function ($hook) use ($name) {
Loading history...
67
            /** @var TemplateHook $hook */
68
            return $this->targetMatches($hook, $name);
69
        });
70
    }
71
72
}