1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psecio\Invoke\Match\Route; |
4
|
|
|
|
5
|
|
|
class Regex extends \Psecio\Invoke\MatchInstance |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Evaluate the provided resource for a match on the provided URI |
9
|
|
|
* |
10
|
|
|
* @param string|\Psecio\Invoke\Resource $data URI to match against |
11
|
|
|
* @return boolean Pass/fail status |
12
|
|
|
*/ |
13
|
|
|
public function evaluate($data) |
14
|
|
|
{ |
15
|
|
|
$regex = $this->getConfig('route'); |
16
|
|
|
$url = ($data instanceof \Psecio\Invoke\Resource) |
17
|
|
|
? $data->getUri() : $data; |
18
|
|
|
|
19
|
|
|
// Find any placeholders and replace them |
20
|
|
|
$split = explode('/', $regex); |
21
|
|
|
$placeholders = []; |
22
|
|
|
foreach ($split as $index => $item) { |
23
|
|
|
if (strpos($item, ':') === 0) { |
24
|
|
|
$placeholders[] = str_replace(':', '', $item); |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
// replace the placeholders for regex location |
29
|
|
|
foreach ($placeholders as $item) { |
30
|
|
|
$regex = str_replace(':'.$item, '(.+?)', $regex); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
$found = preg_match('#^/?'.$regex.'$#', $url, $matches); |
34
|
|
|
|
35
|
|
|
if ($found >= 1) { |
36
|
|
|
// first one is the URL itself, shift off |
37
|
|
|
array_shift($matches); |
38
|
|
|
$params = []; |
39
|
|
|
|
40
|
|
|
// Now match up the placeholders |
41
|
|
|
foreach ($matches as $index => $match) { |
42
|
|
|
if (isset($placeholders[$index])) { |
43
|
|
|
$params[$placeholders[$index]] = $match; |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$this->setParams($params); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return ($found >= 1); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Set the current URI paramaters |
55
|
|
|
* |
56
|
|
|
* @param array $params Paramster set |
57
|
|
|
*/ |
58
|
|
|
public function setParams(array $params) |
59
|
|
|
{ |
60
|
|
|
$this->params = $params; |
|
|
|
|
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** |
64
|
|
|
* Get the current parameter set |
65
|
|
|
* |
66
|
|
|
* @return array Parameter set |
67
|
|
|
*/ |
68
|
|
|
public function getParams() |
69
|
|
|
{ |
70
|
|
|
return $this->params; |
71
|
|
|
} |
72
|
|
|
} |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: