Passed
Push — master ( 91b62f...022aa2 )
by Henri
01:21
created

Helper::getProtocol()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 4
eloc 3
nc 8
nop 0
dl 0
loc 6
rs 10
c 4
b 0
f 0
1
<?php
2
3
namespace HnrAzevedo\Router;
4
5
6
use Exception;
7
8
trait Helper{
9
    use CheckTrait, ControllerTrait;
10
    
11
    private $currentRoute = null;
12
    protected bool $loaded = false;
13
    protected $lastReturn = null;
14
    protected ?string $prefix = null;
15
    protected array $routers = [];
16
17
    public static function current(): ?array
18
    {
19
        return self::getInstance()->currentRoute;
20
    }
21
22
    public static function currentRouteName(): ?string
23
    {
24
        return self::getInstance()->currentRoute['name'];
25
    }
26
27
    public static function currentRouteAction()
28
    {
29
        return self::getInstance()->currentRoute['role'];
30
    }
31
    
32
    protected function getProtocol(): string
33
    {
34
        $protocol = ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')) ? 'ajax' : 'get';
35
        $protocol = (array_key_existS('HTTP_REQUESTED_METHOD',$_SERVER)) ? strtolower($_SERVER['HTTP_REQUESTED_METHOD']) : $protocol;
36
            
37
        return $protocol;
38
    }
39
40
    protected function getData(): ?array
41
    {
42
        return [
43
            'POST' => $_POST,
44
            'GET' => $_GET,
45
            'FILES' => $_FILES,
46
            'PROTOCOL' => $this->getProtocol()
47
        ];
48
    }
49
50
    protected function ControllerForm($controller, string $method, array $values)
51
    {
52
		$this->checkRole();
53
        $method = ($method !== 'method') ? $method : $this->getData()['POST']['role'];
54
        $data = (array_key_exists('data',$values)) ? json_decode($values['data'], true) : [];
55
56
        call_user_func_array([$controller,$method],  $data);
57
    }
58
59
    protected function Controller(string $controll)
60
    {
61
        $data = $this->getData();
62
63
        foreach ($data['GET'] as $name => $value) {
64
            $controll = str_replace('{'.$name.'}',$value,$controll);
65
        }
66
67
        $this->checkControllSettable($controll)->checkControllExist($controll)->checkControllMethod($controll);
68
69
        $controller = ucfirst(explode(':',$controll)[0]);
70
        $controller = new $controller();
71
        $method = explode(':',$controll)[1];
72
73
        if( ($this->getProtocol() == 'form') ){
74
            $this->ControllerForm($controller, $method, $data['POST']);
75
        }else {
76
            $data = (array_key_exists('data',$data['POST'])) ? json_decode($data['POST']['data'], true) : $data['GET'];
77
            call_user_func_array([$controller,$method],  $data);
78
        }
79
80
        return $this;
81
    }    
82
83
    protected function explodeRoutes(bool $bar, string $url ,bool $bar_, string $url_): array
84
    {   
85
        $url = $bar ? substr($url, 0, -1) : $url ;
86
        $url = explode('/',$url);
87
88
        $url_ = $bar_ ? substr($url_, 0, -1) : $url_ ;
89
        $url_ = explode('/',$url_);
90
91
        foreach($url as $ur => $u){
92
            if(substr($u,0,2) === '{?'){
93
                if(!array_key_exists($ur,$url_)){
94
                    $url_[$ur] = '';
95
                };
96
            }
97
        }
98
99
        return ['routeLoop' => $url, 'routeRequest' => $url_];
100
    }
101
102
    protected function run(array $route): bool
103
    {
104
        $this->callOnRoute($route,'beforeAll')->callOnRoute($route,'before');
105
106
        if(is_string($route['role'])){
107
            $this->Controller($route['role'])->callOnRoute($route,'after')->callOnRoute($route,'afterAll');
108
            return true;
109
        }
110
111
        call_user_func_array($route['role'],[$this->getData()['GET']]);
112
113
        $this->callOnRoute($route,'after')->callOnRoute($route,'afterAll');
114
        return true;
115
    }
116
117
    protected function callOnRoute(array $route,string $state)
118
    {
119
        if($route[$state] !== null){
120
            if(is_string($route[$state])){
121
                $this->Controller($route[$state]);
122
            }else{
123
                $route[$state]();
124
            }
125
        }
126
        return $this;
127
    }
128
129
    protected function loadByArray()
130
    {
131
        $currentProtocol = $this->getProtocol();
132
133
        foreach(array_reverse($this->routers) as $r => $route){
134
135
            $this->currentRoute = $route;
136
            $this->currentRoute['name'] = $r;
137
138
            if(!$this->checkProtocol($route['protocol'], $currentProtocol)){
139
                continue;
140
            }
141
142
143
            $this->hasProtocol($route, $currentProtocol);
144
145
            $_SERVER['REQUEST_URI'] = (array_key_exists('REQUEST_URI', $_SERVER)) ? $_SERVER['REQUEST_URI'] : '';
146
147
            $routs = $this->explodeRoutes(
148
                (substr($route['url'],strlen($route['url'])-1,1) === '/') , $route['url'],
149
                (substr($_SERVER['REQUEST_URI'],strlen($_SERVER['REQUEST_URI'])-1,1) === '/') , $_SERVER['REQUEST_URI']
150
            );
151
152
            if(!$this->checkToHiking($route, $routs['routeRequest'], $routs['routeLoop'])){
153
                continue;
154
            }         
155
            
156
            $this->loaded = true;
157
            return $this;
158
        }
159
        
160
        $this->currentRoute = null;
161
	    throw new Exception('Page not found.',404);
162
    }
163
164
    protected function loadByName(string $routName)
165
    {
166
        $currentProtocol = $this->getProtocol();
167
        $this->checkName($routName);
168
        $route = $this->routers[$routName];
169
170
        if(!$this->checkProtocol($route['protocol'], $currentProtocol)){
171
            throw new Exception('Page not found.',404);
172
        }
173
174
        $this->currentRoute = $route;
175
        $this->currentRoute['name'] = $routName;
176
        $this->loaded = true;
177
178
        return $this;            
179
    }
180
181
}
182