Completed
Push — master ( 429167...c8b954 )
by Бабичев
01:47
created

src/Flow/Directives/ForDirective.php (3 issues)

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()
0 ignored issues
show
Possible parse error: non-abstract method defined as abstract
Loading history...
29
    {
30 1
        static::$for[\count(static::$for) - 1] = static::T_ELSE;
0 ignored issues
show
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
The visibility should be declared for property $for.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
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