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

ScriptGenerator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 7
eloc 22
dl 0
loc 59
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getRootContext() 0 3 1
A pushContextNode() 0 4 1
A pushScriptNode() 0 4 1
A getRootScript() 0 3 1
A renderNodeStack() 0 18 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