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
|
|
|
public function __construct(ManipulatorInterface $manipulator) |
19
|
|
|
{ |
20
|
|
|
$this->manipulator = $manipulator; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* {@inheritdoc} |
25
|
|
|
*/ |
26
|
|
|
public function add($targetNodeId, array $data = array()) |
27
|
|
|
{ |
28
|
|
|
$adapter = $this->getManipulator(); |
29
|
|
|
|
30
|
|
|
$adapter->beginTransaction(); |
31
|
|
|
|
32
|
|
|
try { |
33
|
|
|
$adapter->lockTree(); |
34
|
|
|
|
35
|
|
|
$targetNodeInfo = $adapter->getNodeInfo($targetNodeId); |
36
|
|
|
|
37
|
|
|
if (!$targetNodeInfo instanceof NodeInfo) { |
38
|
|
|
throw new ValidationException('Target Node does not exists.'); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
$this->canCreateNewNode($targetNodeInfo); |
42
|
|
|
$this->makeHole($targetNodeInfo); |
43
|
|
|
$newNodeId = $adapter->insert($this->createNewNodeNodeInfo($targetNodeInfo), $data); |
44
|
|
|
|
45
|
|
|
$adapter->commitTransaction(); |
46
|
|
|
} catch (\Exception $e) { |
47
|
|
|
$adapter->rollbackTransaction(); |
48
|
|
|
|
49
|
|
|
throw $e; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
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
|
|
|
protected function getManipulator(): ManipulatorInterface |
78
|
|
|
{ |
79
|
|
|
return $this->manipulator; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|