Completed
Push — master ( 7bc08c...c6d651 )
by Pavel
02:21
created

ApiRoutesResolver::findAndDestroyUserRoutes()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 16
rs 9.4285
cc 3
eloc 9
nc 4
nop 1
1
<?php
2
3
/**
4
 * @copyright   Copyright (c) 2016 ublaboo <[email protected]>
5
 * @author      Pavel Janda <[email protected]>
6
 * @package     Ublaboo
7
 */
8
9
namespace Ublaboo\ApiRouter\DI;
10
11
use Nette;
12
use Nette\Application\Routers\RouteList;
13
use Nette\Application\IRouter;
14
use Ublaboo\ApiRouter\Exception\ApiRouteWrongRouterException;
15
16
class ApiRoutesResolver extends Nette\Object
17
{
18
19
	/**
20
	 * Place REST API routes at the beginnig of all routes
21
	 * @param  IRouter $router
22
	 * @param  array   $routes
23
	 * @return void
24
	 */
25
	public function prepandRoutes(IRouter $router, array $routes)
26
	{
27
		if (empty($routes)) {
28
			return;
29
		}
30
31
		if (!($router instanceof \Traversable) || !($router instanceof \ArrayAccess)) {
32
			throw new ApiRouteWrongRouterException(sprintf(
33
				'ApiRoutesResolver can not add ApiRoutes to your router. Use for example %s instead',
34
				RouteList::class
35
			));
36
		}
37
38
		$user_routes = $this->findAndDestroyUserRoutes($router);
39
40
		/**
41
		 * Add ApiRoutes first
42
		 */
43
		foreach ($routes as $route) {
44
			$router[] = $route;
45
		}
46
47
		/**
48
		 * User routes on second place
49
		 */
50
		foreach ($user_routes as $route) {
51
			$router[] = $route;
52
		}
53
	}
54
55
56
	/**
57
	 * @param  IRouter $router
58
	 * @return array
59
	 */
60
	public function findAndDestroyUserRoutes(IRouter $router)
61
	{
62
		$keys = [];
63
		$return = [];
64
65
		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...
66
			$return[] = $route;
67
			$keys[] = $key;
68
		}
69
70
		foreach (array_reverse($keys) as $key) {
71
			unset($router[$key]);
72
		}
73
74
		return $return;
75
	}
76
77
}
78