Passed
Push — master ( d0d0ee...229425 )
by 世昌
01:51
created

GroupRoutes::add()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 4
nop 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
namespace nebula\application\route;
3
4
use nebula\application\NameFinder;
5
use nebula\component\route\RouteMatcher;
6
use nebula\component\route\RouteCollection;
7
8
/**
9
 * 应用
10
 *
11
 */
12
class GroupRoutes
13
{
14
15
    /**
16
     * 名称查找器
17
     *
18
     * @var NameFinder
19
     */
20
    protected $finder;
21
22
    /**
23
     * 路由集合
24
     *
25
     * @var RouteCollection[]
26
     */
27
    protected $routes = [];
28
29
    /**
30
     * 默认分组
31
     *
32
     * @var string
33
     */
34
    protected $default = 'global:';
35
36
    public function __construct(NameFinder $finder) {
37
        $this->finder = $finder;
38
    }
39
40
    /**
41
     * 注册路由
42
     *
43
     * @param string|null $group
44
     * @param RouteMatcher $router
45
     * @return void
46
     */
47
    public function add(?string $group = null, string $name, RouteMatcher $router)
48
    {
49
        $group =  $group ? $this->finder->getFullName($group) : $this->default;
50
        if (\array_key_exists($group, $this->routes)) {
51
            $this->routes[$group]->add($name, $router);
52
        } else {
53
            $this->routes[$group] = new RouteCollection([$name => $router]);
54
        }
55
    }
56
57
    /**
58
     * 搜索路由
59
     *
60
     * @param string $name
61
     * @return RouteMatcher|null
62
     */
63
    public function find(string $name, ?string $default = null):?RouteMatcher
64
    {
65
        list($group, $name) = $this->finder->info($name, $default ?? $this->default);
66
        if (\array_key_exists($group, $this->routes)) {
67
            return $this->routes[$group]->get($name);
68
        }
69
        return null;
70
    }
71
}
72