HasRoutesTrait   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 8
eloc 17
dl 0
loc 59
ccs 17
cts 17
cp 1
rs 10
c 2
b 1
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getRoutes() 0 2 1
A removeRoute() 0 10 2
A addRoute() 0 17 5
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
	 * @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 3
	public function addRoute( RouteInterface $route ) {
43 3
		$routes = $this->getRoutes();
44 3
		$name = $route->getAttribute( 'name' );
45
46 3
		if ( in_array( $route, $routes, true ) ) {
47 1
			throw new ConfigurationException( 'Attempted to register a route twice.' );
48
		}
49
50 3
		if ( $name !== '' ) {
51 2
			foreach ( $routes as $registered ) {
52 1
				if ( $name === $registered->getAttribute( 'name' ) ) {
53 1
					throw new ConfigurationException( "The route name \"$name\" is already registered." );
54
				}
55
			}
56
		}
57
58 3
		$this->routes[] = $route;
59 3
	}
60
61
	/**
62
	 * Remove a route.
63
	 *
64
	 * @param  RouteInterface $route
65
	 * @return void
66
	 */
67 1
	public function removeRoute( RouteInterface $route ) {
68 1
		$routes = $this->getRoutes();
69
70 1
		$index = array_search( $route, $routes, true );
71
72 1
		if ( $index === false ) {
73 1
			return;
74
		}
75
76 1
		$this->routes = array_values( Arr::except( $routes, $index ) );
77 1
	}
78
}
79