Completed
Push — master ( 0ea9e7...aef2ed )
by Anton
14s
created

Controller   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 335
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 14

Test Coverage

Coverage 65.45%

Importance

Changes 0
Metric Value
dl 0
loc 335
ccs 72
cts 110
cp 0.6545
rs 8.3999
c 0
b 0
f 0
wmc 38
lcom 1
cbo 14

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A checkPrivilege() 0 8 3
C checkAccept() 0 42 8
A setFile() 0 11 2
A getFile() 0 7 2
A setReflection() 0 17 2
A getReflection() 0 7 2
A assign() 0 5 1
A getData() 0 7 2
A jsonSerialize() 0 4 1
B __toString() 0 27 2
A checkMethod() 0 8 3
C run() 0 61 9
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Controller;
12
13
use Bluz\Application\Application;
14
use Bluz\Application\Exception\ForbiddenException;
15
use Bluz\Application\Exception\NotAcceptableException;
16
use Bluz\Application\Exception\NotAllowedException;
17
use Bluz\Auth\EntityInterface;
18
use Bluz\Common\Helper;
19
use Bluz\Proxy\Acl;
20
use Bluz\Proxy\Cache;
21
use Bluz\Proxy\Request;
22
use Bluz\Proxy\Response;
23
use Bluz\Response\ResponseTrait;
24
use Bluz\View\View;
25
26
/**
27
 * Statement
28
 *
29
 * @package  Bluz\Controller
30
 * @author   Anton Shevchuk
31
 *
32
 * @method void attachment(string $file)
33
 * @method void denied()
34
 * @method void disableLayout()
35
 * @method void disableView()
36
 * @method Controller dispatch(string $module, string $controller, array $params = [])
37
 * @method void redirect(string $url)
38
 * @method void redirectTo(string $module, string $controller, array $params = [])
39
 * @method void reload()
40
 * @method void useJson()
41
 * @method void useLayout($layout)
42
 * @method EntityInterface user()
43
 */
44
class Controller implements \JsonSerializable
45
{
46
    use Helper;
47
    use ResponseTrait;
48
49
    /**
50
     * @var string
51
     */
52
    protected $module;
53
54
    /**
55
     * @var string
56
     */
57
    protected $controller;
58
59
    /**
60
     * @var string
61
     */
62
    protected $template;
63
64
    /**
65
     * @var string
66
     */
67
    protected $file;
68
69
    /**
70
     * @var Reflection
71
     */
72
    protected $reflection;
73
74
    /**
75
     * @var Data
76
     */
77
    protected $data;
78
79
    /**
80
     * One of HTML, JSON or empty string
81
     * @var string
82
     */
83
    protected $render = 'HTML';
84
85
    /**
86
     * Constructor of Statement
87
     *
88
     * @param string $module
89
     * @param string $controller
90
     */
91 639
    public function __construct($module, $controller)
92
    {
93 639
        $this->module = $module;
94 639
        $this->controller = $controller;
95 639
        $this->template = $controller . '.phtml';
96
97
        // initial default helper path
98 639
        $this->addHelperPath(__DIR__ . '/Helper/');
99 639
    }
100
101
    /**
102
     * Check `Privilege`
103
     *
104
     * @throws ForbiddenException
105
     */
106 9
    public function checkPrivilege()
107
    {
108 9
        if ($privilege = $this->getReflection()->getPrivilege()) {
109
            if (!Acl::isAllowed($this->module, $privilege)) {
110
                throw new ForbiddenException;
111
            }
112
        }
113 8
    }
114
115
    /**
116
     * Check `Method`
117
     *
118
     * @throws NotAllowedException
119
     */
120 9
    public function checkMethod()
121
    {
122 9
        if ($this->getReflection()->getMethod()
123
            && !in_array(Request::getMethod(), $this->getReflection()->getMethod())) {
124
            Response::setHeader('Allow', join(',', $this->getReflection()->getMethod()));
125
            throw new NotAllowedException;
126
        }
127 8
    }
128
129
    /**
130
     * Check `Accept`
131
     *
132
     * @throws NotAcceptableException
133
     */
134 9
    public function checkAccept()
135
    {
136
        // all ok for CLI
137 9
        if (PHP_SAPI == 'cli') {
138 9
            return;
139
        }
140
141
        $allowAccept = $this->getReflection()->getAccept();
142
143
        // some controllers hasn't @accept tag
144
        if (!$allowAccept) {
145
            // but by default allow just HTML output
146
            $allowAccept = [Request::TYPE_HTML, Request::TYPE_ANY];
147
        }
148
149
        // get Accept with high priority
150
        $accept = Request::getAccept($allowAccept);
151
152
        // some controllers allow any type (*/*)
153
        // and client doesn't send Accept header
154
        if (in_array(Request::TYPE_ANY, $allowAccept) && !$accept) {
155
            // all OK, controller should realize logic for response
156
            return;
157
        }
158
159
        // some controllers allow just selected types
160
        // choose MIME type by browser accept header
161
        // filtered by controller @accept
162
        // switch statement for this logic
163
        switch ($accept) {
164
            case Request::TYPE_ANY:
165
            case Request::TYPE_HTML:
166
                // HTML response with layout
167
                break;
168
            case Request::TYPE_JSON:
169
                // JSON response
170
                $this->template = null;
171
                break;
172
            default:
173
                throw new NotAcceptableException;
174
        }
175
    }
176
177
    /**
178
     * __invoke
179
     *
180
     * @param array $params
181
     * @return Data
182
     * @throws ControllerException
183
     */
184 8
    public function run($params = []) // : array
185
    {
186
        // initial variables for use inside controller
187 8
        $module = $this->module;
188 8
        $controller = $this->controller;
189
190 8
        $cacheKey = 'data.' . Cache::prepare($this->module . '.' . $this->controller)
191 8
            . '.' . md5(http_build_query($params));
192
193 8
        $cacheTime = $this->getReflection()->getCache();
194
195 8
        if ($cacheTime && $cached = Cache::get($cacheKey)) {
196
            return $cached;
197
        }
198
199
        /**
200
         * @var \closure $controllerClosure
201
         */
202 8
        $controllerClosure = include $this->getFile();
203
204 8
        if (!is_callable($controllerClosure)) {
205
            throw new ControllerException("Controller is not callable '{$module}/{$controller}'");
206
        }
207
208
        // process params
209 8
        $params = $this->getReflection()->params($params);
210
211
        // call Closure or Controller
212 8
        $result = $controllerClosure(...$params);
213
214
        // switch statement for result of Closure run
215
        switch (true) {
216 6
            case ($result === false):
217
                // return "false" is equal to disable view and layout
218
                $this->disableLayout();
219
                $this->disableView();
220
                break;
221 6
            case is_string($result):
222
                // return string variable is equal to change view template
223
                $this->template = $result;
224
                break;
225 6
            case is_array($result):
226
                // return associative array is equal to setup view data
227 3
                $this->getData()->setFromArray($result);
228 3
                break;
229
            case ($result instanceof Controller):
230
                $this->getData()->setFromArray($result->getData()->toArray());
231
                break;
232
        }
233
234 6
        if ($cacheTime) {
235
            Cache::set(
236
                $cacheKey,
237
                $this->getData(),
238
                $cacheTime,
239
                ['system', 'data', Cache::prepare($this->module . '.' . $this->controller)]
240
            );
241
        }
242
243 6
        return $this->getData();
244
    }
245
246
    /**
247
     * Setup controller file
248
     *
249
     * @return void
250
     * @throws ControllerException
251
     */
252 639
    protected function setFile()
253
    {
254 639
        $path = Application::getInstance()->getPath();
255 639
        $file = $path . '/modules/' . $this->module . '/controllers/' . $this->controller . '.php';
256
257 639
        if (!file_exists($file)) {
258 3
            throw new ControllerException("Controller file not found '{$this->module}/{$this->controller}'", 404);
259
        }
260
261 639
        $this->file = $file;
262 639
    }
263
264
    /**
265
     * Get controller file path
266
     * @return string
267
     */
268 639
    protected function getFile() // : string
269
    {
270 639
        if (!$this->file) {
271 639
            $this->setFile();
272
        }
273 639
        return $this->file;
274
    }
275
276
    /**
277
     * Retrieve reflection for anonymous function
278
     * @return void
279
     * @throws \Bluz\Common\Exception\ComponentException
280
     */
281 639
    protected function setReflection()
282
    {
283
        // cache for reflection data
284 639
        $cacheKey = 'reflection.' . Cache::prepare($this->module . '.' . $this->controller);
285 639
        if (!$reflection = Cache::get($cacheKey)) {
286 639
            $reflection = new Reflection($this->getFile());
287 639
            $reflection->process();
288
289 639
            Cache::set(
290
                $cacheKey,
291
                $reflection,
292 639
                Cache::TTL_NO_EXPIRY,
293 639
                ['system', 'reflection', Cache::prepare($this->module . '.' . $this->controller)]
294
            );
295
        }
296 639
        $this->reflection = $reflection;
297 639
    }
298
    
299
    /**
300
     * Get Reflection
301
     * @return Reflection
302
     */
303 639
    public function getReflection() // : Reflection
304
    {
305 639
        if (!$this->reflection) {
306 639
            $this->setReflection();
307
        }
308 639
        return $this->reflection;
309
    }
310
311
    /**
312
     * Assign key/value pair to Data object
313
     * @param  string $key
314
     * @param  mixed  $value
315
     * @return Controller
316
     */
317
    public function assign($key, $value)
318
    {
319
        $this->getData()->set($key, $value);
320
        return $this;
321
    }
322
    
323
    /**
324
     * Get controller Data container
325
     *
326
     * @return Data
327
     */
328 6
    public function getData()
329
    {
330 6
        if (!$this->data) {
331 6
            $this->data = new Data();
332
        }
333 6
        return $this->data;
334
    }
335
336
    /**
337
     * Specify data which should be serialized to JSON
338
     *
339
     * @return Data
340
     */
341
    public function jsonSerialize()
342
    {
343
        return $this->getData();
344
    }
345
346
    /**
347
     * Magic cast to string
348
     *
349
     * @return string
350
     */
351 2
    public function __toString()
352
    {
353 2
        if (!$this->template) {
354
            return '';
355
        }
356
357
        // $view for use in closure
358 2
        $view = new View();
359
360 2
        $path = Application::getInstance()->getPath();
361
362
        // setup additional helper path
363 2
        $view->addHelperPath($path . '/layouts/helpers');
364
365
        // setup additional partial path
366 2
        $view->addPartialPath($path . '/layouts/partial');
367
368
        // setup default path
369 2
        $view->setPath($path . '/modules/' . $this->module . '/views');
370
371
        // setup template
372 2
        $view->setTemplate($this->template);
373
374
        // setup data
375 2
        $view->setFromArray($this->getData()->toArray());
376 2
        return $view->render();
377
    }
378
}
379