Passed
Push — main ( 1c3482...173990 )
by Daniel
02:28
created

ScriptGenerator::renderNodeStack()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 18
ccs 11
cts 11
cp 1
rs 9.9332
c 0
b 0
f 0
cc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace MallardDuck\DynamicEcho\ScriptGenerator;
4
5
use Illuminate\Support\Collection;
6
use MallardDuck\DynamicEcho\Collections\ContextNodeCollection;
7
use MallardDuck\DynamicEcho\ScriptGenerator\Nodes\ContextNode;
8
use MallardDuck\DynamicEcho\ScriptGenerator\Nodes\ScriptNode;
9
10
/**
11
 * Class ScriptGenerator
12
 *
13
 * Generates the Echo javascript for both the context and event scripts.
14
 *
15
 * @package MallardDuck\DynamicEcho
16
 */
17
class ScriptGenerator
18
{
19
    private ContextNodeCollection $contextNodeStack;
20
    private Collection $scriptNodeStack;
21
22 6
    public function __construct()
23
    {
24 6
        $this->contextNodeStack = new ContextNodeCollection();
25
26 6
        $this->scriptNodeStack = new Collection([
27 6
            ScriptNodeBuilder::getRootEchoNode(),
28
        ]);
29 6
    }
30
31 1
    public function pushContextNode(ContextNode $node): self
32
    {
33 1
        $this->contextNodeStack->push($node);
34 1
        return $this;
35
    }
36
37 1
    public function getRootContext(): string
38
    {
39 1
        return $this->contextNodeStack->toJson();
40
    }
41
42 1
    public function pushScriptNode(ScriptNode $node): self
43
    {
44 1
        $this->scriptNodeStack->push($node);
45 1
        return $this;
46
    }
47
48
    /**
49
     * Outputs the entire generated Echo script code.
50
     *
51
     * @return string
52
     */
53 2
    public function getRootScript(): string
54
    {
55 2
        return $this->renderNodeStack($this->scriptNodeStack);
56
    }
57
58 2
    private function renderNodeStack(Collection $nodeStack): string
59
    {
60
        /**
61
         * @var string
62
         */
63 2
        $results = '';
64 2
        $count = $nodeStack->count();
65 2
        $nodeStack->map(static function ($item) use (&$results, &$count) {
66 2
            $results .= (string) $item;
67 2
            --$count;
68 2
            if (0 === $count) {
69 2
                $results .= ";\n";
70
            } else {
71 1
                $results .= "\n";
72
            }
73 2
        });
74
75 2
        return $results;
76
    }
77
}
78