Completed
Push — master ( 4e3eed...0c868b )
by Thomas
02:41
created

Indexer::deIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Gielfeldt\TransactionalPHP;
4
5
/**
6
 * Class Indexer
7
 *
8
 * @package Gielfeldt\TransactionalPHP
9
 */
10
class Indexer
11
{
12
    /**
13
     * @var int[]
14
     */
15
    protected $index = [];
16
17
    /**
18
     * @var Connection
19
     */
20
    protected $connection;
21
22
    /**
23
     * Indexer constructor.
24
     *
25
     * @param Connection $connection
26
     */
27 3
    public function __construct(Connection $connection)
28
    {
29 3
        $this->connection = $connection;
30 3
    }
31
32
    /**
33
     * Get connection.
34
     *
35
     * @return Connection
36
     */
37 1
    public function getConnection()
38
    {
39 1
        return $this->connection;
40
    }
41
42
    /**
43
     * Index operation.
44
     *
45
     * @param string $key
46
     *   The key to index undeer.
47
     * @param Operation $operation
48
     *   The operation to index.
49
     *
50
     * @return Operation
51
     *   The operation indexed.
52
     */
53 2
    public function index($key, Operation $operation)
54
    {
55 2
        $this->index[$key][$operation->idx($this->connection)] = $operation;
56 2
        $indexer = $this;
57
        $operation->onCommit(function ($operation) use ($key, $indexer) {
58
            $indexer->deIndex($key, $operation);
59 2
        });
60 2
        $operation->onRollback(function ($operation) use ($key, $indexer) {
61
            $indexer->deIndex($key, $operation);
62 2
        });
63 2
        return $operation;
64
    }
65
66
    /**
67
     * De-index operation.
68
     *
69
     * @param string $key
70
     *   The key to index undeer.
71
     * @param Operation $operation
72
     *   The operation to index.
73
     *
74
     * @return Operation
75
     *   The operation de-indexed.
76
     */
77 1
    public function deIndex($key, Operation $operation)
78
    {
79 1
        unset($this->index[$key][$operation->idx($this->connection)]);
80 1
        return $operation;
81
    }
82
83
    /**
84
     * Lookup operation.
85
     *
86
     * @param string $key
87
     *   The key to look up.
88
     *
89
     * @return array
90
     *   Operations.
91
     */
92 2
    public function lookup($key)
93
    {
94 2
        return isset($this->index[$key]) ? $this->index[$key] : [];
95
    }
96
}
97