1
|
|
|
<?php |
2
|
|
|
namespace Autocomplete\Container\Trie; |
3
|
|
|
|
4
|
|
|
use Autocomplete\Contract\Container\NodeInterface; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* @implements NodeInterface |
8
|
|
|
*/ |
9
|
|
|
class Node implements NodeInterface |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var mixed |
13
|
|
|
*/ |
14
|
|
|
private $value; |
15
|
|
|
/** |
16
|
|
|
* @var Node |
17
|
|
|
*/ |
18
|
|
|
private $children = []; |
19
|
|
|
/** |
20
|
|
|
* boolean|string |
21
|
|
|
*/ |
22
|
|
|
private $endNode; |
23
|
|
|
|
24
|
|
|
public function __construct($value) |
25
|
|
|
{ |
26
|
|
|
$this->value = $value; |
27
|
|
|
$this->endNode = false; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function getEndNode() |
31
|
|
|
{ |
32
|
|
|
return $this->endNode; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function setEndNode($value) |
36
|
|
|
{ |
37
|
|
|
$this->endNode = $value; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function getChild($string) |
41
|
|
|
{ |
42
|
|
|
foreach ($this->children as $child) { |
|
|
|
|
43
|
|
|
if ($child->value == $string) { |
44
|
|
|
return $child; |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
return false; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
public function getClosest($prefix) |
51
|
|
|
{ |
52
|
|
|
$child = $this; |
53
|
|
|
$prefix = str_split($prefix); |
54
|
|
|
foreach ($prefix as $char) { |
55
|
|
|
if ($child) { |
56
|
|
|
$child = $child->getChild($char); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
return $child; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
public function getPostfix($prefix, $postFixes = []) |
63
|
|
|
{ |
64
|
|
|
if ($this->endNode) { |
65
|
|
|
$postFixes[] = $this->endNode; |
66
|
|
|
} |
67
|
|
|
foreach ($this->children as $child) { |
|
|
|
|
68
|
|
|
$postFixes = $child->getPostfix($prefix, $postFixes); |
69
|
|
|
} |
70
|
|
|
return $postFixes; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function addChild($name) |
74
|
|
|
{ |
75
|
|
|
if ($this->getChild($name)) { |
76
|
|
|
return $this->getChild($name); |
|
|
|
|
77
|
|
|
} |
78
|
|
|
$child = new Node($name); |
79
|
|
|
$this->children[] = $child; |
80
|
|
|
return $child; |
|
|
|
|
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public function addSuffix($suffix) |
84
|
|
|
{ |
85
|
|
|
$method = new Method\AddSuffix; |
86
|
|
|
return $method->execute($suffix, $this); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
public function hasWord($word) |
90
|
|
|
{ |
91
|
|
|
$method = new Method\HasWord; |
92
|
|
|
return $method->execute($word, $this); |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
public function hasPrefix($prefix) |
96
|
|
|
{ |
97
|
|
|
$method = new Method\HasPrefix; |
98
|
|
|
return $method->execute($prefix, $this); |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
public function graph(array &$arr, $level = 0) |
102
|
|
|
{ |
103
|
|
|
$arr[$level][] = $this->value; |
104
|
|
|
$level++; |
105
|
|
|
foreach ($this->children as $child) { |
|
|
|
|
106
|
|
|
$child->graph($arr, $level); |
107
|
|
|
} |
108
|
|
|
} |
109
|
|
|
} |
110
|
|
|
|