ApiRoutesResolver   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 1
dl 0
loc 54
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B prepandRoutes() 0 29 6
A findAndDestroyUserRoutes() 0 16 3
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @copyright   Copyright (c) 2016 ublaboo <[email protected]>
7
 * @author      Pavel Janda <[email protected]>
8
 * @package     Ublaboo
9
 */
10
11
namespace Ublaboo\ApiRouter\DI;
12
13
use Nette\Application\IRouter;
14
use Nette\Application\Routers\RouteList;
15
use Ublaboo\ApiRouter\Exception\ApiRouteWrongRouterException;
16
17
class ApiRoutesResolver
18
{
19
20
	/**
21
	 * Place REST API routes at the beginnig of all routes
22
	 */
23
	public function prepandRoutes(IRouter $router, array $routes): void
24
	{
25
		if (empty($routes)) {
26
			return;
27
		}
28
29
		if (!($router instanceof \Traversable) || !($router instanceof \ArrayAccess)) {
30
			throw new ApiRouteWrongRouterException(sprintf(
31
				'ApiRoutesResolver can not add ApiRoutes to your router. Use for example %s instead',
32
				RouteList::class
33
			));
34
		}
35
36
		$user_routes = $this->findAndDestroyUserRoutes($router);
37
38
		/**
39
		 * Add ApiRoutes first
40
		 */
41
		foreach ($routes as $route) {
42
			$router[] = $route;
43
		}
44
45
		/**
46
		 * User routes on second place
47
		 */
48
		foreach ($user_routes as $route) {
49
			$router[] = $route;
50
		}
51
	}
52
53
54
	public function findAndDestroyUserRoutes(IRouter $router): array
55
	{
56
		$keys = [];
57
		$return = [];
58
59
		foreach ($router as $key => $route) {
0 ignored issues
show
Bug introduced by
The expression $router of type object<Nette\Application\IRouter> is not traversable.
Loading history...
60
			$return[] = $route;
61
			$keys[] = $key;
62
		}
63
64
		foreach (array_reverse($keys) as $key) {
65
			unset($router[$key]);
66
		}
67
68
		return $return;
69
	}
70
}
71