LazyLoadCollection   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
c 2
b 0
f 0
lcom 1
cbo 2
dl 0
loc 48
ccs 12
cts 12
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A createCollection() 0 4 1
A items() 0 10 2
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