|
1
|
|
|
<?php |
|
2
|
|
|
namespace Skansing\Escapology\RouteFileParser; |
|
3
|
|
|
|
|
4
|
|
|
use \Skansing\Escapology\RouteFileParser; |
|
5
|
|
|
|
|
6
|
|
|
class Regex implements RouteFileParser { |
|
7
|
|
|
|
|
8
|
|
|
const |
|
9
|
|
|
VERB = 0, |
|
10
|
|
|
URI = 1, |
|
11
|
|
|
REGEX_PREFIX = '~^(?:', |
|
12
|
|
|
REGEX_SEPARATOR = '|', |
|
13
|
|
|
REGEX_AFFIX = ')$~'; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Parses the passed route file and return a specialized array |
|
17
|
|
|
* |
|
18
|
|
|
* @param string $file Absolute path to the route file |
|
19
|
|
|
* @throws \Exception If $file is missing or empty |
|
20
|
|
|
* @return Array Lookup table for routes and a combined regex |
|
21
|
|
|
*/ |
|
22
|
9 |
|
public function digest($file) |
|
23
|
|
|
{ |
|
24
|
2 |
|
$routesData = $this->getRoutesData($file); |
|
25
|
9 |
|
$routeRegexes = []; |
|
26
|
|
|
for($i = 0; $i < count($routesData) -1; ++$i) { |
|
27
|
|
|
$this->setRouteRegexData($routeRegexes, $routesData, $i); |
|
28
|
3 |
|
$routeRegexes[$routesData[$i][self::VERB]] .= $routesData[$i][self::URI] . self::REGEX_SEPARATOR; |
|
29
|
1 |
|
} |
|
30
|
|
|
$this->setRouteRegexData($routeRegexes, $routesData, $i); |
|
31
|
9 |
|
$routeRegexes[$routesData[$i][self::VERB]] .= $routesData[$i][self::URI]; |
|
32
|
|
|
foreach($routeRegexes as $verb => $regex) { |
|
33
|
4 |
|
$routeRegexes[$verb] .= self::REGEX_AFFIX; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
9 |
|
return $routeRegexes; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Gets the routes data and returns it |
|
41
|
|
|
* |
|
42
|
|
|
* @param $file |
|
43
|
|
|
* @throws \Exception If $file is missing or empty |
|
44
|
|
|
*/ |
|
45
|
10 |
|
private function getRoutesData($file) { |
|
46
|
|
|
if(file_exists($file) === false) { |
|
47
|
|
|
throw new \Exception('Route file not found.'); |
|
48
|
|
|
} |
|
49
|
|
|
$routesData = require $file; |
|
50
|
10 |
|
if(empty($routesData)) { |
|
51
|
|
|
throw new \Exception('Route file is empty.'); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
9 |
|
return $routesData; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* Sets the group regex string with the constant REGEX_PREFIX between each route |
|
59
|
|
|
* |
|
60
|
|
|
* @param array &$routeRegexes |
|
61
|
|
|
* @param array &$routesData |
|
62
|
|
|
* @param int $index |
|
63
|
|
|
*/ |
|
64
|
4 |
|
private function setRouteRegexData(&$routeRegexes, &$routesData, $index) { |
|
65
|
1 |
|
if(isset($routeRegexes[$routesData[$index][self::VERB]]) === false) { |
|
66
|
4 |
|
$routeRegexes[$routesData[$index][self::VERB]] = self::REGEX_PREFIX; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |