Completed
Push — master ( 0c868b...cdf250 )
by Thomas
02:42
created

Indexer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 87
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 5
Bugs 0 Features 2
Metric Value
wmc 6
c 5
b 0
f 2
lcom 1
cbo 1
dl 0
loc 87
ccs 19
cts 19
cp 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getConnection() 0 4 1
A deIndex() 0 5 1
A lookup() 0 4 2
A index() 0 12 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 4
    public function __construct(Connection $connection)
28
    {
29 4
        $this->connection = $connection;
30 4
    }
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 3
    public function index($key, Operation $operation)
54
    {
55 3
        $this->index[$key][$operation->idx($this->connection)] = $operation;
56 3
        $indexer = $this;
57
        $operation->onCommit(function ($operation) use ($key, $indexer) {
58 1
            $indexer->deIndex($key, $operation);
59 3
        });
60 3
        $operation->onRollback(function ($operation) use ($key, $indexer) {
61 1
            $indexer->deIndex($key, $operation);
62 3
        });
63 3
        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 2
    public function deIndex($key, Operation $operation)
78
    {
79 2
        unset($this->index[$key][$operation->idx($this->connection)]);
80 2
        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 3
    public function lookup($key)
93
    {
94 3
        return isset($this->index[$key]) ? $this->index[$key] : [];
95
    }
96
}
97