Completed
Push — master ( 19ca72...4bd58a )
by Kirill
02:15
created

IdentityMap   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 58
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A fetch() 0 8 2
A push() 0 8 2
A identities() 0 4 1
A clearIdentityMap() 0 9 2
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