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

AddStrategyAbstract::getManipulator()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
crap 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\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