1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Bavix\Flow\Directives; |
4
|
|
|
|
5
|
|
|
use Bavix\Flow\Directive; |
6
|
|
|
use Bavix\Flow\Loop; |
7
|
|
|
use Bavix\Helpers\Arr; |
8
|
|
|
|
9
|
|
|
class ForDirective extends Directive |
10
|
|
|
{ |
11
|
|
|
|
12
|
|
|
const T_END = 1; |
13
|
|
|
const T_ELSE = 2; |
14
|
|
|
|
15
|
|
|
protected static $for = []; |
16
|
|
|
protected static $loops = []; |
17
|
|
|
|
18
|
4 |
|
public static function loop($key, $rows = null) |
19
|
|
|
{ |
20
|
4 |
|
if (!\array_key_exists($key, static::$loops)) |
21
|
|
|
{ |
22
|
4 |
|
static::$loops[$key] = new Loop($rows); |
23
|
|
|
} |
24
|
|
|
|
25
|
4 |
|
return static::$loops[$key]; |
26
|
|
|
} |
27
|
|
|
|
28
|
1 |
|
public static function else() |
|
|
|
|
29
|
|
|
{ |
30
|
1 |
|
static::$for[\count(static::$for) - 1] = static::T_ELSE; |
|
|
|
|
31
|
1 |
|
} |
32
|
|
|
|
33
|
6 |
|
public function render(): string |
34
|
|
|
{ |
35
|
6 |
|
Arr::push(static::$for, static::T_END); |
36
|
|
|
|
37
|
6 |
|
$init = ''; |
38
|
6 |
|
$rows = $this->data['rows']['code']; |
39
|
|
|
|
40
|
6 |
|
if (\count($this->data['rows']['lexer']['tokens']) > 1) |
41
|
|
|
{ |
42
|
|
|
$rows = $this->randVariable(); |
43
|
|
|
$init = $rows . '=' . $this->data['rows']['code'] . ';'; |
44
|
|
|
} |
45
|
|
|
|
46
|
6 |
|
$loop = $this->randVariable(); |
47
|
6 |
|
$key = $this->data['key']['code'] ?? $this->randVariable(); |
48
|
6 |
|
$row = $this->data['row']['code']; |
49
|
|
|
|
50
|
6 |
|
return '<?php ' . $init . 'if (!empty(' . $rows . ')):' . |
51
|
6 |
|
'\Bavix\Flow\Directives\ForDirective::loop(\'' . $loop . '\', ' . $rows . ');' . |
52
|
6 |
|
'foreach (' . $rows . ' as ' . $key . ' => ' . $row . '): ' . |
53
|
6 |
|
'$this->loop = \Bavix\Flow\Directives\ForDirective::loop(\'' . $loop . '\');' . |
54
|
6 |
|
'$this->loop->next(' . $key . ');?>'; |
55
|
|
|
} |
56
|
|
|
|
57
|
5 |
|
public function endDirective(): string |
58
|
|
|
{ |
59
|
5 |
|
if (Arr::pop(static::$for) === static::T_ELSE) |
60
|
|
|
{ |
61
|
1 |
|
return '<?php unset($this->loop); endif; ?>'; |
62
|
|
|
} |
63
|
|
|
|
64
|
4 |
|
return '<?php unset($this->loop); endforeach; endif; ?>'; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
} |
68
|
|
|
|