Completed
Push — master ( 188443...8f2ae0 )
by Maik
06:56
created

AbstractRouter::hasRoute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
namespace Nkey\Caribu\Mvc\Router;
3
4
use Nkey\Caribu\Mvc\Controller\AbstractController;
5
use Nkey\Caribu\Mvc\Controller\Request;
6
use Nkey\Caribu\Mvc\Application;
7
8
abstract class AbstractRouter {
9
	
10
	/**
11
	 * Application instance
12
	 * 
13
	 * @var Application
14
	 */
15
	private $application;
16
	
17 2
	public function setApplication(Application $application)
18
	{
19 2
		$this->application = $application;
20 2
		foreach($this->routes as $routeName => $controller) {
21 2
			$this->application->registerController($controller, $routeName);
22
		}
23 2
	}
24
	
25
	/**
26
	 * @var array
27
	 */
28
	private $routes;
29
	
30 2
	public function addRoute(string $name, AbstractController $controller)
31
	{
32 2
		$this->routes[$name] = $controller;
33 2
	}
34
	
35
	/**
36
	 * Checks wether a route exists
37
	 * 
38
	 * @param string $name
39
	 * @return bool
40
	 */
41 2
	public function hasRoute(string $name)
42
	{
43 2
		return key_exists($name, $this->routes);
44
	}
45
	
46
	/**
47
	 * 
48
	 * @param string $name
49
	 * @throws RouterException
50
	 * @return AbstractController
51
	 */
52 1
	private function getRoute(string $name)
53
	{
54 1
		if(!$this->hasRoute($name)) {
55
			throw new RouterException("Router {$router} is not registered");
56
		}
57
		
58 1
		return $this->routes[$name];
59
	}
60
	
61
	/**
62
	 * Route the existing request into a new controller
63
	 * 
64
	 * @param string $name The name of route
65
	 * @param Request $request The existing request instance
66
	 * @return \Nkey\Caribu\Mvc\Controller\AbstractController
67
	 */
68 1
	public function route(string $name, Request $request)
69
	{
70 1
		$parts = \explode('/', $request->getOrigin());
71 1
		$found = false;
72 1
		for($i = 0; $i < count($parts); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
73 1
			if($parts[$i] === $name && isset($parts[$i+1])) {
74
				$request->setAction($parts[$i+1]);
75
				$found = true;
76
			}
77
		}
78 1
		if(!$found) {
79 1
			$request->setAction("index");
80
		}
81 1
		return $this->getRoute($name);
82
	}
83
}