Passed
Branch master (9026fd)
by Bartko
02:45
created

AddStrategyAbstract   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 19
c 0
b 0
f 0
dl 0
loc 69
rs 10
ccs 19
cts 19
cp 1
wmc 5

3 Methods

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