LazyLoadedIndex::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Storeman\VaultLayout;
4
5
use Storeman\Index\Index;
6
use Storeman\Index\IndexObject;
7
8
/**
9
 * Allows for an index to be lazy-loaded when its actually required using a provided loader callback.
10
 * This might be used in situations where you don't know in advance if the index content is actually needed and helps
11
 * to reduce the runtime.
12
 */
13
class LazyLoadedIndex extends Index
14
{
15
    /**
16
     * @var callable
17
     */
18
    protected $indexLoader;
19
20
    public function __construct(callable $indexLoader)
21
    {
22
        parent::__construct();
23
24
        $this->rootNode = null;
25
        $this->indexLoader = $indexLoader;
26
    }
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function addObject(IndexObject $indexObject): Index
32
    {
33
        $this->loadIndex();
34
35
        return parent::addObject($indexObject);
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function getObjectByPath(string $path): ?IndexObject
42
    {
43
        $this->loadIndex();
44
45
        return parent::getObjectByPath($path);
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function getObjectByBlobId(string $blobId): ?IndexObject
52
    {
53
        $this->loadIndex();
54
55
        return parent::getObjectByBlobId($blobId);
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function count(): int
62
    {
63
        $this->loadIndex();
64
65
        return parent::count();
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function getIterator(): \Traversable
72
    {
73
        $this->loadIndex();
74
75
        return parent::getIterator();
76
    }
77
78
    /**
79
     * Lazy-loads the actual index from the injected loader.
80
     */
81
    protected function loadIndex()
82
    {
83
        if ($this->rootNode === null)
84
        {
85
            $index = call_user_func($this->indexLoader);
86
87
            if (!($index instanceof Index))
88
            {
89
                throw new \LogicException();
90
            }
91
92
            $this->rootNode = $index->rootNode;
93
        }
94
    }
95
}
96