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

Loop::loop()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
ccs 10
cts 10
cp 1
rs 9.4285
cc 1
eloc 9
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Advmaker\BladeLoop;
4
5
class Loop
6
{
7
    /**
8
     * The array that is being iterated
9
     *
10
     * @var array
11
     */
12
    protected $items = [];
13
14
    /**
15
     * The data for the current $loop item
16
     *
17
     * @var array
18
     */
19
    protected $data;
20
21
    /**
22
     * Instantiates the class
23
     *
24
     * @param array $items The array that's being iterated
25
     */
26 15
    public function __construct($items)
27
    {
28 15
        $this->items = $items;
29 15
        $this->init($items);
30 15
    }
31
32
    /**
33
     * Sets the array to monitor
34
     *
35
     * @param array $items The array that's being iterated
36
     */
37 15
    protected function init($items)
38
    {
39 15
        $total = count($items);
40 15
        $this->data = [
41 15
            'index'     => -1,
42 15
            'revindex'  => $total,
43
            'length'    => $total
44 15
        ];
45 15
    }
46
47
    /**
48
     * Sets the parent loop
49
     *
50
     * @param Loop $parentLoop
51
     */
52 3
    public function setParentLoop(Loop $parentLoop)
53
    {
54 3
        $this->data['parent'] = $parentLoop;
55 3
    }
56
57
    /**
58
     * Return array that must be iterated.
59
     *
60
     * @return array
61
     */
62 15
    public function getItems()
63
    {
64 15
        return $this->items;
65
    }
66
67
    /**
68
     * Magic method to access the loop data properties
69
     *
70
     * @param $key
71
     *
72
     * @return mixed
73
     */
74 15
    public function __get($key)
75
    {
76 15
        return $this->data[$key];
77
    }
78
79
    /**
80
     * To be called first in a loop before anything else
81
     */
82 15
    public function loop()
83
    {
84 15
        $this->data['index']++;
85 15
        $this->data['index1'] = $this->data['index'] + 1;
86 15
        $this->data['revindex']--;
87 15
        $this->data['revindex1'] = $this->data['revindex'] + 1;
88
89 15
        $this->data['even'] = $this->data['index'] % 2 === 0;
90 15
        $this->data['odd'] = ! $this->data['even'];
91
92 15
        $this->data['first'] = $this->data['index'] === 0;
93 15
        $this->data['last'] = $this->data['revindex'] === 0;
94 15
    }
95
}
96