Completed
Push — master ( 2b0446...afde37 )
by Bartko
04:01 queued 01:40
created

AddStrategyAbstract   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 70
rs 10
c 0
b 0
f 0
ccs 20
cts 20
cp 1
wmc 5
lcom 1
cbo 2

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B add() 0 27 3
canCreateNewNode() 0 1 ?
makeHole() 0 1 ?
createNewNodeNodeInfo() 0 1 ?
A getAdapter() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace StefanoTree\NestedSet\AddStrategy;
6
7
use StefanoTree\Exception\ValidationException;
8
use StefanoTree\NestedSet\Adapter\AdapterInterface;
9
use StefanoTree\NestedSet\NodeInfo;
10
11
abstract class AddStrategyAbstract implements AddStrategyInterface
12
{
13
    private $adapter;
14
15
    /**
16
     * @param AdapterInterface $adapter
17
     */
18 8
    public function __construct(AdapterInterface $adapter)
19
    {
20 8
        $this->adapter = $adapter;
21 8
    }
22
23
    /**
24
     * {@inheritdoc}
25
     */
26 8
    public function add($targetNodeId, array $data = array())
27
    {
28 8
        $adapter = $this->getAdapter();
29
30 8
        $adapter->beginTransaction();
31
        try {
32 8
            $adapter->lockTree();
33
34 8
            $targetNodeInfo = $adapter->getNodeInfo($targetNodeId);
35
36 8
            if (!$targetNodeInfo instanceof NodeInfo) {
37 1
                throw new ValidationException('Target Node does not exists.');
38
            }
39
40 7
            $this->canCreateNewNode($targetNodeInfo);
41 5
            $this->makeHole($targetNodeInfo);
42 5
            $newNodeId = $adapter->insert($this->createNewNodeNodeInfo($targetNodeInfo), $data);
43
44 5
            $adapter->commitTransaction();
45 3
        } catch (\Exception $e) {
46 3
            $adapter->rollbackTransaction();
47
48 3
            throw $e;
49
        }
50
51 5
        return $newNodeId;
52
    }
53
54
    /**
55
     * @param NodeInfo $targetNode
56
     *
57
     * @throws ValidationException If cannot move node
58
     */
59
    abstract protected function canCreateNewNode(NodeInfo $targetNode): void;
60
61
    /**
62
     * @param NodeInfo $targetNode
63
     */
64
    abstract protected function makeHole(NodeInfo $targetNode): void;
65
66
    /**
67
     * @param NodeInfo $targetNode
68
     *
69
     * @return NodeInfo
70
     */
71
    abstract protected function createNewNodeNodeInfo(NodeInfo $targetNode): NodeInfo;
72
73
    /**
74
     * @return AdapterInterface
75
     */
76 8
    protected function getAdapter(): AdapterInterface
77
    {
78 8
        return $this->adapter;
79
    }
80
}
81