| Total Complexity | 13 |
| Total Lines | 108 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | <?php |
||
| 11 | class UriMatcher extends MatcherHelper |
||
| 12 | { |
||
| 13 | |||
| 14 | /** |
||
| 15 | * 匹配Uri |
||
| 16 | * |
||
| 17 | * @var string |
||
| 18 | */ |
||
| 19 | protected $uri; |
||
| 20 | /** |
||
| 21 | * 匹配的正则 |
||
| 22 | * |
||
| 23 | * @var string |
||
| 24 | */ |
||
| 25 | protected $match; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * URI中的参数 |
||
| 29 | * |
||
| 30 | * @var RouteMatcher[] |
||
| 31 | */ |
||
| 32 | protected $parameter; |
||
| 33 | |||
| 34 | public function __construct(string $uri, string $match, array $parameter) |
||
| 35 | { |
||
| 36 | $this->uri = $uri; |
||
| 37 | $this->match = $match; |
||
| 38 | $this->parameter = $parameter; |
||
| 39 | } |
||
| 40 | |||
| 41 | /** |
||
| 42 | * 匹配URL |
||
| 43 | * |
||
| 44 | * @param string $url |
||
| 45 | * @param boolean $ignoreCase |
||
| 46 | * @return array|null |
||
| 47 | */ |
||
| 48 | public function match(string $url, bool $ignoreCase = true):?array |
||
| 49 | { |
||
| 50 | $match = '#^'. $this->match.'$#'. ($ignoreCase?'i':''); |
||
| 51 | if (preg_match($match, $url, $parameter)) { |
||
| 52 | array_shift($parameter); |
||
| 53 | return $parameter; |
||
| 54 | } |
||
| 55 | return null; |
||
| 56 | } |
||
| 57 | |||
| 58 | /** |
||
| 59 | * 构建参数 |
||
| 60 | * |
||
| 61 | * @param array $matchParameter |
||
| 62 | * @return array |
||
| 63 | */ |
||
| 64 | public function buildParamter(array $matchParameter):array |
||
| 65 | { |
||
| 66 | $parameters = []; |
||
| 67 | foreach ($this->parameter as $index => $parameter) { |
||
| 68 | if (isset($matchParameter[$index])) { |
||
| 69 | $value = $parameter->unpackValue($matchParameter[$index]); |
||
| 70 | } else { |
||
| 71 | $value = $parameter->getDefaultValue(); |
||
| 72 | } |
||
| 73 | $parameters[$parameter->getIndexName()] = $value; |
||
| 74 | } |
||
| 75 | return $parameters; |
||
| 76 | } |
||
| 77 | |||
| 78 | public function getParameter(string $name):?Parameter { |
||
| 79 | foreach ($this->parameter as $parameter) { |
||
| 80 | if ($parameter->getIndexName() === $name) { |
||
| 81 | return $parameter; |
||
| 82 | } |
||
| 83 | } |
||
| 84 | return null; |
||
| 85 | } |
||
| 86 | |||
| 87 | /** |
||
| 88 | * Get 匹配的正则 |
||
| 89 | * |
||
| 90 | * @return string |
||
| 91 | */ |
||
| 92 | public function getMatch() |
||
| 93 | { |
||
| 94 | return $this->match; |
||
| 95 | } |
||
| 96 | |||
| 97 | /** |
||
| 98 | * Set 匹配的正则 |
||
| 99 | * |
||
| 100 | * @param string $match 匹配的正则 |
||
| 101 | * |
||
| 102 | * @return self |
||
| 103 | */ |
||
| 104 | public function setMatch(string $match) |
||
| 109 | } |
||
| 110 | |||
| 111 | /** |
||
| 112 | * Get 匹配Uri |
||
| 113 | * |
||
| 114 | * @return string |
||
| 115 | */ |
||
| 116 | public function getUri() |
||
| 119 | } |
||
| 120 | } |
||
| 121 |