Completed
Push — feature/fixing_cost ( 414fbf...99877f )
by Laurent
01:40
created

RouteManager::loadGuards()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace FlightLog\Infrastructure\Common\Routes;
5
6
7
use FlightLog\Http\Web\Response\Redirect;
8
use FlightLog\Http\Web\Response\Response;
9
use User;
10
11
final class RouteManager
12
{
13
14
    /**
15
     * @var array|Route[]
16
     */
17
    private $routes;
18
19
    /**
20
     * @var \DoliDB
21
     */
22
    private $db;
23
24
    /**
25
     * @var Guard[]|array
26
     */
27
    private $guards;
28
29
    public function __construct(\DoliDB $db)
30
    {
31
        $this->routes = [];
32
        $this->db = $db;
33
    }
34
35
36
    /**
37
     * @param Route $route
38
     *
39
     * @throws \Exception
40
     */
41
    public function add(Route $route){
42
        if(isset($this->routes[$route->getName()])){
43
            throw new \Exception('Route exists');
44
        }
45
46
        $this->routes[$route->getName()] = $route;
47
    }
48
49
    /**
50
     * @param array $routes
51
     *
52
     * @throws \Exception
53
     */
54
    public function load(array $routes){
55
        foreach($routes as $currentRoute){
56
            $this->add($currentRoute);
57
        }
58
    }
59
60
    /**
61
     * @param array|Guard[] $routesGuards
62
     */
63
    public function loadGuards($routesGuards)
64
    {
65
        foreach($routesGuards as $guard){
66
            $this->guards[$guard->getRouteName()] = $guard;
67
        }
68
    }
69
70
    /**
71
     * Is the user authorized to reach the endpoint?
72
     * @param User $user
73
     * @param $routeName
74
     * @return bool
75
     */
76
    public function isAuthorized(User $user, $routeName){
77
        if(!isset($this->guards[$routeName])){
78
            return true;
79
        }
80
81
        return $this->guards[$routeName]->__invoke($user);
82
    }
83
84
    /**
85
     * @param string $name
86
     *
87
     * @param User $user
88
     *
89
     * @return Redirect|Response
90
     *
91
     * @throws \Exception
92
     */
93
    public function __invoke($name, User $user)
94
    {
95
        if(!isset($this->routes[$name])){
96
            throw new \Exception('Route not found');
97
        }
98
99
        if(!$this->isAuthorized($user, $name)){
100
            throw new \Exception('Action not allowed');
101
        }
102
103
        $route = $this->routes[$name];
104
105
        $controllerName = $route->getController();
106
        $controller = new $controllerName($this->db);
107
108
        return call_user_func([$controller, $route->getMethod()]);
109
    }
110
111
112
}