| 1 |
<?php |
| 2 |
/** |
| 3 |
* @package WPEmerge |
| 4 |
* @author Atanas Angelov <hi@atanas.dev> |
| 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 |
* @codeCoverageIgnore |
| 30 |
* @return RouteInterface[] |
| 31 |
*/ |
| 32 |
public function getRoutes() { |
| 33 |
return $this->routes; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Add a route. |
| 38 |
* |
| 39 |
* @param RouteInterface $route |
| 40 |
* @return void |
| 41 |
*/ |
| 42 |
public function addRoute( RouteInterface $route ) { |
| 43 |
$routes = $this->getRoutes(); |
| 44 |
$name = $route->getAttribute( 'name' ); |
| 45 |
|
| 46 |
if ( in_array( $route, $routes, true ) ) { |
| 47 |
throw new ConfigurationException( 'Attempted to register a route twice.' ); |
| 48 |
} |
| 49 |
|
| 50 |
if ( $name !== '' ) { |
| 51 |
foreach ( $routes as $registered ) { |
| 52 |
if ( $name === $registered->getAttribute( 'name' ) ) { |
| 53 |
throw new ConfigurationException( "The route name \"$name\" is already registered." ); |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
$this->routes[] = $route; |
| 59 |
} |
| 60 |
|
| 61 |
/** |
| 62 |
* Remove a route. |
| 63 |
* |
| 64 |
* @param RouteInterface $route |
| 65 |
* @return void |
| 66 |
*/ |
| 67 |
public function removeRoute( RouteInterface $route ) { |
| 68 |
$routes = $this->getRoutes(); |
| 69 |
|
| 70 |
$index = array_search( $route, $routes, true ); |
| 71 |
|
| 72 |
if ( $index === false ) { |
| 73 |
return; |
| 74 |
} |
| 75 |
|
| 76 |
$this->routes = array_values( Arr::except( $routes, $index ) ); |
| 77 |
} |
| 78 |
} |
| 79 |
|