IdentityMap::clearIdentityMap()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 8
cp 0
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * This file is part of Platform package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Karma\Platform\Support;
11
12
/**
13
 * Trait IdentityMap
14
 * @package Karma\Platform\Support
15
 */
16
trait IdentityMap
17
{
18
    /**
19
     * @var array
20
     */
21
    protected $items = [];
22
23
    /**
24
     * @param string $class
25
     * @param string $id
26
     * @param \Closure $resolver
27
     * @return mixed
28
     */
29
    protected function fetch(string $class, string $id, \Closure $resolver)
30
    {
31
        if (!array_key_exists($id, $this->items[$class] ?? [])) {
32
            $this->push($class, $id, $resolver());
33
        }
34
35
        return $this->items[$class][$id];
36
    }
37
38
    /**
39
     * @param string $class
40
     * @param string $id
41
     * @param $data
42
     */
43
    protected function push(string $class, string $id, $data)
44
    {
45
        if (!array_key_exists($class, $this->items)) {
46
        $this->items[$class] = [];
47
    }
48
49
        $this->items[$class][$id] = $data;
50
    }
51
52
    /**
53
     * @param string $class
54
     * @return \Traversable
55
     */
56
    protected function identities(string $class): \Traversable
57
    {
58
        return new \ArrayIterator($this->items[$class] ?? []);
59
    }
60
61
    /**
62
     * @param null|string $class
63
     */
64
    protected function clearIdentityMap(?string $class): void
65
    {
66
        if ($class === null) {
67
            $this->items = [];
68
            return;
69
        }
70
71
        $this->items[$class] = [];
72
    }
73
}
74