-
Notifications
You must be signed in to change notification settings - Fork 1
/
NestedSet.php
62 lines (51 loc) · 1.86 KB
/
NestedSet.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
namespace Vhood\TreeType\Type;
use Vhood\TreeType\Contract\TreeType;
use Vhood\TreeType\Converter\NestedSetConverter;
use Vhood\TreeType\Exception\InvalidStructureException;
class NestedSet implements TreeType
{
private $nodes;
private $leftValueKey;
private $rightValueKey;
private $idKey;
/**
* @param array $flatTree
* @param string $leftValueKey
* @param string $rightValueKey
* @param null|string $idKey
* @return void
* @throws InvalidStructureException
*/
public function __construct(array $flatTree, $leftValueKey = 'lft', $rightValueKey = 'rgt', $idKey = null)
{
foreach ($flatTree as $index => $node) {
if (!array_key_exists($leftValueKey, $node)) {
throw new InvalidStructureException("Node $index has no left value field");
}
if (!array_key_exists($rightValueKey, $node)) {
throw new InvalidStructureException("Node $index has no right value field");
}
if (!is_integer($node[$leftValueKey])) {
throw new InvalidStructureException("Node $index has incorrect left value type");
}
if (!is_integer($node[$rightValueKey])) {
throw new InvalidStructureException("Node $index has incorrect right value type");
}
if ($idKey && !array_key_exists($idKey, $node)) {
throw new InvalidStructureException("Node $index has no id field");
}
}
$this->leftValueKey = $leftValueKey;
$this->rightValueKey = $rightValueKey;
$this->idKey = $idKey;
$this->nodes = array_values($flatTree);
}
/**
* {@inheritdoc}
*/
public function initConverter()
{
return new NestedSetConverter($this->nodes, $this->leftValueKey, $this->rightValueKey, $this->idKey);
}
}