Passed
Push — master ( a2340d...9d7d2b )
by butschster
06:32
created

ImportContext   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 85.19%

Importance

Changes 0
Metric Value
wmc 11
eloc 21
dl 0
loc 59
ccs 23
cts 27
cp 0.8519
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A on() 0 3 1
A getImports() 0 12 4
A __construct() 0 3 1
A resolve() 0 10 3
A add() 0 13 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Stempler\Transform\Context;
6
7
use Spiral\Core\Exception\LogicException;
8
use Spiral\Stempler\Builder;
9
use Spiral\Stempler\Node\AttributedInterface;
10
use Spiral\Stempler\Node\Template;
11
use Spiral\Stempler\Transform\Import\ImportInterface;
12
use Spiral\Stempler\VisitorContext;
13
14
/**
15
 * Manages currently open scope of imports (via nested tags).
16
 */
17
final class ImportContext
18
{
19 59
    private function __construct(
20
        private readonly VisitorContext $ctx
21
    ) {
22 59
    }
23
24 38
    public function add(ImportInterface $import): void
25
    {
26 38
        $node = $this->ctx->getParentNode();
27 38
        if (!$node instanceof AttributedInterface) {
28
            throw new LogicException(\sprintf(
29
                'Unable to create import on node without attribute storage (%s)',
30
                \get_debug_type($node)
31
            ));
32
        }
33
34 38
        $imports = $node->getAttribute(self::class, []);
35 38
        $imports[] = $import;
36 38
        $node->setAttribute(self::class, $imports);
37
    }
38
39
    /**
40
     * Resolve imported element template.
41
     */
42 55
    public function resolve(Builder $builder, string $name): ?Template
43
    {
44 55
        foreach ($this->getImports() as $import) {
45 38
            $tpl = $import->resolve($builder, $name);
46 36
            if ($tpl !== null) {
47 36
                return $tpl;
48
            }
49
        }
50
51 48
        return null;
52
    }
53
54
    /**
55
     * Return all imports assigned to the given path.
56
     *
57
     * @return ImportInterface[]
58
     */
59 55
    public function getImports(): array
60
    {
61 55
        $imports = [];
62 55
        foreach (\array_reverse($this->ctx->getScope()) as $node) {
63 55
            if ($node instanceof AttributedInterface) {
64 55
                foreach ($node->getAttribute(self::class, []) as $import) {
65 38
                    $imports[] = $import;
66
                }
67
            }
68
        }
69
70 55
        return $imports;
71
    }
72
73 59
    public static function on(VisitorContext $ctx): self
74
    {
75 59
        return new self($ctx);
76
    }
77
}
78