Completed
Push — master ( bc9a85...6641a7 )
by Maksim (Ellrion)
7s
created

LoopFactory::endLoop()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Advmaker\BladeLoop;
4
5
class LoopFactory
6
{
7
8
    /**
9
     * The stack of Loop instances
10
     *
11
     * @var Loop[] $stack
12
     */
13
    protected $stack = [];
14
15
    /**
16
     * Creates a new loop with the given array and adds it to the stack
17
     *
18
     * @param array $items The array that will be iterated
19
     */
20 15
    public function newLoop($items)
21
    {
22 15
        $this->addLoopStack(new Loop($items));
23 15
    }
24
25
    /**
26
     * Adds a Loop to the stack
27
     *
28
     * @param Loop $stackItem
29
     */
30 15
    protected function addLoopStack(Loop $stackItem)
31
    {
32
        // Check stack for parent loop to register it with this loop
33 15
        if (count($this->stack) > 0) {
34 3
            $stackItem->setParentLoop(last($this->stack));
35 3
        }
36
37 15
        array_push($this->stack, $stackItem);
38 15
    }
39
40
    /**
41
     * Returns the stack
42
     *
43
     * @return array
44
     */
45
    public function getStack()
46
    {
47
        return $this->stack;
48
    }
49
50
    /**
51
     * getLastStack method
52
     *
53
     * @return Loop
54
     */
55 15
    public function getLastStack()
56
    {
57 15
        return end($this->stack);
58
    }
59
60
    /**
61
     * Resets the stack
62
     */
63
    public function reset()
64
    {
65
        $this->stack = [];
66
    }
67
68
    /**
69
     * To be called first inside the foreach loop. Returns the current loop
70
     *
71
     * @return Loop $current The current loop data
72
     */
73 15
    public function loop()
74
    {
75 15
        $current = end($this->stack);
76 15
        $current->before();
77
78 15
        return $current;
79
    }
80
81
    /**
82
     * To be called before the end of the loop
83
     */
84 15
    public function looped()
85
    {
86 15
        if (!empty($this->stack)) {
87 15
            end($this->stack)->after();
88 15
        }
89 15
    }
90
91
    /**
92
     * Should be called after the loop has finished
93
     *
94
     * @param $loop
95
     */
96 15
    public function endLoop(&$loop)
97
    {
98 15
        array_pop($this->stack);
99 15
        if (count($this->stack) > 0) {
100
            // This loop was inside another loop. We persist the loop variable and assign back the parent loop
101 3
            $loop = end($this->stack);
102 3
        } else {
103
            // This loop was not inside another loop. We remove the var
104 15
            $loop = null;
105
        }
106 15
    }
107
}
108