|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* @package WPEmerge |
|
4
|
|
|
* @author Atanas Angelov <[email protected]> |
|
5
|
|
|
* @copyright 2017-2019 Atanas Angelov |
|
6
|
|
|
* @license https://www.gnu.org/licenses/gpl-2.0.html GPL-2.0 |
|
7
|
|
|
* @link https://wpemerge.com/ |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace WPEmerge\Routing; |
|
11
|
|
|
|
|
12
|
|
|
use WPEmerge\Exceptions\ConfigurationException; |
|
13
|
|
|
use WPEmerge\Support\Arr; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* Allow objects to have routes |
|
17
|
|
|
*/ |
|
18
|
|
|
trait HasRoutesTrait { |
|
19
|
|
|
/** |
|
20
|
|
|
* Array of registered routes |
|
21
|
|
|
* |
|
22
|
|
|
* @var RouteInterface[] |
|
23
|
|
|
*/ |
|
24
|
|
|
protected $routes = []; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* Get routes. |
|
28
|
|
|
* |
|
29
|
|
|
* @return RouteInterface[] |
|
30
|
|
|
*/ |
|
31
|
|
|
public function getRoutes() { |
|
32
|
|
|
return $this->routes; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Add a route. |
|
37
|
|
|
* |
|
38
|
|
|
* @param RouteInterface $route |
|
39
|
|
|
* @return void |
|
40
|
|
|
*/ |
|
41
|
1 |
|
public function addRoute( RouteInterface $route ) { |
|
42
|
1 |
|
$routes = $this->getRoutes(); |
|
43
|
1 |
|
$name = $route->getAttribute( 'name' ); |
|
44
|
|
|
|
|
45
|
1 |
|
foreach ( $routes as $registered ) { |
|
46
|
1 |
|
if ( $registered === $route ) { |
|
47
|
|
|
throw new ConfigurationException( 'Attempted to register a route twice.' ); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
1 |
|
if ( $name !== '' && $name === $registered->getAttribute( 'name' ) ) { |
|
51
|
1 |
|
throw new ConfigurationException( "The route name \"$name\" is already registered." ); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
1 |
|
$this->routes[] = $route; |
|
56
|
1 |
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Remove a route. |
|
60
|
|
|
* |
|
61
|
|
|
* @param RouteInterface $route |
|
62
|
|
|
* @return void |
|
63
|
|
|
*/ |
|
64
|
1 |
|
public function removeRoute( RouteInterface $route ) { |
|
65
|
1 |
|
$routes = $this->getRoutes(); |
|
66
|
|
|
|
|
67
|
1 |
|
$index = array_search( $route, $routes, true ); |
|
68
|
|
|
|
|
69
|
1 |
|
if ( $index === false ) { |
|
70
|
1 |
|
return; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
1 |
|
$this->routes = array_values( Arr::except( $routes, $index ) ); |
|
74
|
1 |
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|