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
|
|
|
|