1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Divergence package. |
4
|
|
|
* |
5
|
|
|
* (c) Henry Paradiz <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Divergence\Routing; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Tree style router with path traversal |
15
|
|
|
* @author Henry Paradiz <[email protected]> |
16
|
|
|
*/ |
17
|
|
|
class Path |
18
|
|
|
{ |
19
|
|
|
public array $pathStack; |
20
|
|
|
public array $requestPath; |
21
|
|
|
protected array $_path; |
22
|
|
|
|
23
|
72 |
|
public function __construct(string $path) |
24
|
|
|
{ |
25
|
72 |
|
$this->setPath($path); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* If path is /my/example this function returns my the first time and example the second time |
30
|
|
|
* False is returned once you run out of path. |
31
|
|
|
* @return string|false |
32
|
|
|
*/ |
33
|
65 |
|
public function peekPath() |
34
|
|
|
{ |
35
|
65 |
|
return count($this->_path) ? $this->_path[0] : false; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* The shifted value, or null; if array is empty or is not an array |
40
|
|
|
* |
41
|
|
|
* @return mixed |
42
|
|
|
*/ |
43
|
67 |
|
public function shiftPath() |
44
|
|
|
{ |
45
|
67 |
|
return array_shift($this->_path); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Returns the path stack |
50
|
|
|
* |
51
|
|
|
* @return array |
52
|
|
|
*/ |
53
|
2 |
|
public function getPath() |
54
|
|
|
{ |
55
|
2 |
|
return $this->_path; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Adds a value to the path stack so that the next shiftPath or peekPath is what you provide here |
60
|
|
|
* |
61
|
|
|
* @param string $string |
62
|
|
|
* @return int Count of path stack after appending to it |
63
|
|
|
*/ |
64
|
2 |
|
public function unshiftPath($string) |
65
|
|
|
{ |
66
|
2 |
|
return array_unshift($this->_path, $string); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Private makes this class immutable |
71
|
|
|
* |
72
|
|
|
* @param string $requestURI |
73
|
|
|
* @return void |
74
|
|
|
*/ |
75
|
72 |
|
protected function setPath($requestURI = null) |
76
|
|
|
{ |
77
|
72 |
|
if (!isset($this->pathStack)) { |
78
|
72 |
|
$parsedURL = parse_url($requestURI); |
79
|
72 |
|
$this->pathStack = $this->requestPath = explode('/', ltrim($parsedURL['path'], '/')); |
80
|
|
|
} |
81
|
|
|
|
82
|
72 |
|
$this->_path = isset($path) ? $path : $this->pathStack; |
|
|
|
|
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|