LazyLoadCollection::createCollection()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
nc 1
cc 1
eloc 2
nop 1
crap 1
1
<?php
2
3
namespace Nayjest\Collection\Extended;
4
5
use Nayjest\Collection\CollectionInterface;
6
use Nayjest\Collection\CollectionTrait;
7
use Nayjest\Collection\Collection;
8
9
/**
10
 * Collection with deferred initialization (lazy load).
11
 *
12
 * Initialization callback executes when accessing collection items first time.
13
 *
14
 */
15
class LazyLoadCollection implements CollectionInterface
16
{
17
    use CollectionTrait {
18
        CollectionTrait::items as private itemsInternal;
19
    }
20
21
    private $initialized = false;
22
    private $initializer;
23
24
    /**
25
     * Constructor.
26
     *
27
     * Callback passed to $initializer argument
28
     * will be executed when accessing collection items first time.
29
     *
30
     * @param callable $initializer callable that returns collection items
31
     */
32 9
    public function __construct(callable $initializer)
33
    {
34 9
        $this->initializer = $initializer;
35 9
    }
36
37 9
    protected function &items()
38
    {
39 9
        if (!$this->initialized) {
40 9
            $data = &$this->itemsInternal();
41 9
            $data = call_user_func($this->initializer);
42 9
            $this->initialized = true;
43 9
        }
44
45 9
        return $this->itemsInternal();
46
    }
47
48
    /**
49
     * Creates collection of items.
50
     *
51
     * Override it if you need to implement
52
     * derived collection that requires specific initialization.
53
     *
54
     * @param array $items
55
     *
56
     * @return static
57
     */
58 1
    protected function createCollection(array $items)
59
    {
60 1
        return new Collection($items);
61
    }
62
}
63