LazyDbReferenceCollection::getIterator()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
1
<?php
2
/**
3
 * Created by gerk on 13.11.16 11:21
4
 */
5
6
namespace PeekAndPoke\Component\Slumber\Data;
7
8
use PeekAndPoke\Component\Collections\ArrayCollection;
9
10
/**
11
 * @author Karsten J. Gerber <[email protected]>
12
 */
13
class LazyDbReferenceCollection extends ArrayCollection
14
{
15
    /**
16
     * @param mixed $offset
17
     *
18
     * @return mixed
19
     */
20 2
    public function offsetGet($offset)
21
    {
22 2
        $item = parent::offsetGet($offset);
23
24 2
        if ($item instanceof LazyDbReference) {
25 2
            return $item->getValue();
26
        }
27
28
        return $item;
29
    }
30
31
    /**
32
     * @return \Iterator
33
     */
34 2
    public function getIterator()
35
    {
36
        // we need a special iterator in order to unwrap LazyDbReference instances
37 2
        return new LazyDbReferenceIterator(
38 2
            new \ArrayIterator($this->data)
39
        );
40
    }
41
}
42
43
/**
44
 * @internal
45
 *
46
 * @author Karsten J. Gerber <[email protected]>
47
 */
48
class LazyDbReferenceIterator extends \IteratorIterator
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
49
{
50 2
    public function rewind()
51
    {
52 2
        parent::rewind();
53
54
        // skip all elements that cannot be found in the database
55 2
        while ($this->valid() && $this->current() === null) {
56
            $this->next();
57
        }
58 2
    }
59
60 2
    public function next()
61
    {
62
        // skip all elements that cannot be found in the database
63 2
        while ($this->valid()) {
64 2
            parent::next();
65
66 2
            if ($this->current() !== null) {
67 2
                return;
68
            }
69
        }
70 2
    }
71
72
    /**
73
     * @return mixed
74
     */
75 2
    public function current()
76
    {
77 2
        $item = parent::current();
78
79 2
        if ($item instanceof LazyDbReference) {
80 2
            return $item->getValue();
81
        }
82
83 2
        return $item;
84
    }
85
}
86