1
|
|
|
<?php |
2
|
|
|
namespace nebula\application\module; |
3
|
|
|
|
4
|
|
|
/** |
5
|
|
|
* 模块命名处理器 |
6
|
|
|
*/ |
7
|
|
|
class NameFinder |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* 已知全部全名 |
11
|
|
|
* |
12
|
|
|
* @var array |
13
|
|
|
*/ |
14
|
|
|
protected $knownsFullName = []; |
15
|
|
|
|
16
|
|
|
public function add(string $name, string $version) |
17
|
|
|
{ |
18
|
|
|
$version = $this->formatVersion($version); |
19
|
|
|
if (!\in_array($name, $this->knownsFullName)) { |
20
|
|
|
$this->knownsFullName[$name][$version] = $name.':'.$version; |
21
|
|
|
uksort($this->knownsFullName[$name], [$this, 'sort']); |
22
|
|
|
} |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* 拆分名称 |
27
|
|
|
* [namespace/]name[:version]:data -> [namespace/name:version,data] |
28
|
|
|
* |
29
|
|
|
* @param string $name |
30
|
|
|
* @param string|null $default |
31
|
|
|
* @return array |
32
|
|
|
*/ |
33
|
|
|
public function info(string $name, ?string $default = null):array |
34
|
|
|
{ |
35
|
|
|
$rpos = \strrpos($name, ':'); |
36
|
|
|
if ($rpos > 0) { |
37
|
|
|
$module = substr($name, 0, $rpos); |
38
|
|
|
$name = \substr($name, $rpos+1); |
39
|
|
|
$moduleFull = $this->getFullName($module); |
40
|
|
|
return [$moduleFull, $name]; |
41
|
|
|
} |
42
|
|
|
if ($rpos === 0) { |
43
|
|
|
return [$default, substr($name, 1)]; |
44
|
|
|
} |
45
|
|
|
return [$default, $name]; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function getFullName(string $name):string |
49
|
|
|
{ |
50
|
|
|
$version = null; |
51
|
|
|
$hasVersion = false; |
52
|
|
|
if (\strpos($name, ':')) { |
53
|
|
|
$hasVersion = true; |
54
|
|
|
list($name, $version) = \explode(':', $name, 2); |
55
|
|
|
} |
56
|
|
|
$name = $this->getLikeName($name); |
57
|
|
|
if (\array_key_exists($version, $this->knownsFullName[$name])) { |
58
|
|
|
return $this->knownsFullName[$name][$version]; |
59
|
|
|
} |
60
|
|
|
return $hasVersion?$name.':'.$version:end($this->knownsFullName[$name]); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
protected function getLikeName(string $name):string |
64
|
|
|
{ |
65
|
|
|
$names = []; |
66
|
|
|
foreach (array_keys($this->knownsFullName) as $keyName) { |
67
|
|
|
if (\strpos($keyName, $name) !== false) { |
68
|
|
|
$names[] = $keyName; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
if (count($names) === 0) { |
72
|
|
|
throw new \Exception(\sprintf('name %s not exist', $name)); |
73
|
|
|
} |
74
|
|
|
if (count($names) > 1) { |
75
|
|
|
throw new \Exception(\sprintf('conflict name %s', $name)); |
76
|
|
|
} |
77
|
|
|
return $names[0]; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
|
81
|
|
|
protected function sort(string $a, string $b) |
82
|
|
|
{ |
83
|
|
|
return \version_compare($a, $b); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
protected function formatVersion(string $version) |
87
|
|
|
{ |
88
|
|
|
$version = \strtolower($version); |
89
|
|
|
if (\strpos($version, 'v') === 0) { |
90
|
|
|
return substr($version, 1); |
91
|
|
|
} |
92
|
|
|
return $version; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|