Regex::evaluate()   B
last analyzed

Complexity

Conditions 8
Paths 24

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 8.0515
c 0
b 0
f 0
cc 8
nc 24
nop 1
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;
0 ignored issues
show
Bug introduced by
The property params does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
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
}