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
|
3 |
|
public function __construct() |
23
|
|
|
{ |
24
|
3 |
|
$this->contextNodeStack = new ContextNodeCollection(); |
25
|
|
|
|
26
|
3 |
|
$this->scriptNodeStack = new Collection([ |
27
|
3 |
|
ScriptNodeBuilder::getRootEchoNode(), |
28
|
|
|
]); |
29
|
3 |
|
} |
30
|
|
|
|
31
|
|
|
public function pushContextNode(ContextNode $node): self |
32
|
|
|
{ |
33
|
|
|
$this->contextNodeStack->push($node); |
34
|
|
|
return $this; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function getRootContext(): string |
38
|
|
|
{ |
39
|
|
|
return $this->contextNodeStack->toJson(); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function pushScriptNode(ScriptNode $node): self |
43
|
|
|
{ |
44
|
|
|
$this->scriptNodeStack->push($node); |
45
|
|
|
return $this; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Outputs the entire generated Echo script code. |
50
|
|
|
* |
51
|
|
|
* @return string |
52
|
|
|
*/ |
53
|
|
|
public function getRootScript(): string |
54
|
|
|
{ |
55
|
|
|
return $this->renderNodeStack($this->scriptNodeStack); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private function renderNodeStack(Collection $nodeStack): string |
59
|
|
|
{ |
60
|
|
|
/** |
61
|
|
|
* @var string |
62
|
|
|
*/ |
63
|
|
|
$results = ''; |
64
|
|
|
$count = $nodeStack->count(); |
65
|
|
|
$nodeStack->map(static function ($item) use (&$results, &$count) { |
66
|
|
|
$results .= (string) $item; |
67
|
|
|
--$count; |
68
|
|
|
if (0 === $count) { |
69
|
|
|
$results .= ";\n"; |
70
|
|
|
} else { |
71
|
|
|
$results .= "\n"; |
72
|
|
|
} |
73
|
|
|
}); |
74
|
|
|
|
75
|
|
|
return $results; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|