|
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
|
|
|
|