Completed
Push — master ( 0d121e...4e7962 )
by Maksim (Ellrion)
9s
created

LoopFactory::reset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2
Metric Value
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Advmaker\BladeLoop;
4
5
class LoopFactory
6
{
7
    /**
8
     * The stack of Loop instances
9
     *
10
     * @var Loop[] $stack
11
     */
12
    protected $stack = [];
13
14
    /**
15
     * Creates a new loop with the given array and adds it to the stack
16
     *
17
     * @param array $items The array that will be iterated
18
     * @return Loop
19
     */
20 15
    public function newLoop($items)
21
    {
22 15
        $loop = new Loop($items);
23
24
        // Check stack for parent loop to register it with this loop
25 15
        if (count($this->stack) > 0) {
26 3
            $loop->setParentLoop(last($this->stack));
27 3
        }
28
29 15
        array_push($this->stack, $loop);
30
31 15
        return $loop;
32
    }
33
34
    /**
35
     * Should be called after the loop has finished
36
     *
37
     * @param $loop
38
     */
39 15
    public function endLoop(&$loop)
40
    {
41 15
        array_pop($this->stack);
42
43 15
        if (count($this->stack) > 0) {
44
            // This loop was inside another loop. We persist the loop variable and assign back the parent loop
45 3
            $loop = end($this->stack);
46 3
        } else {
47
            // This loop was not inside another loop. We remove the var
48 15
            $loop = null;
49
        }
50 15
    }
51
52
    /**
53
     * To be called first inside the foreach loop. Returns the current loop
54
     *
55
     * @return Loop $current The current loop data
56
     */
57 15
    public function loop()
58
    {
59 15
        $current = end($this->stack);
60 15
        $current->loop();
61
62 15
        return $current;
63
    }
64
}
65