Completed
Pull Request — master (#409)
by Anton
05:45
created

Controller   B

Complexity

Total Complexity 38

Size/Duplication

Total Lines 335
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 13

Test Coverage

Coverage 65.14%

Importance

Changes 0
Metric Value
dl 0
loc 335
ccs 71
cts 109
cp 0.6514
rs 8.3999
c 0
b 0
f 0
wmc 38
lcom 1
cbo 13

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A checkPrivilege() 0 8 3
A setFile() 0 11 2
A getFile() 0 7 2
A assign() 0 5 1
A getData() 0 7 2
A jsonSerialize() 0 4 1
B __toString() 0 27 2
C checkAccept() 0 42 8
C run() 0 61 9
A setMeta() 0 18 2
A getMeta() 0 7 2
A checkMethod() 0 7 3
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 Meta
71
     */
72
    protected $meta;
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 650
    public function __construct($module, $controller)
92
    {
93 650
        $this->module = $module;
94 650
        $this->controller = $controller;
95 650
        $this->template = $controller . '.phtml';
96
97
        // initial default helper path
98 650
        $this->addHelperPath(__DIR__ . '/Helper/');
99 650
    }
100
101
    /**
102
     * Check `Privilege`
103
     *
104
     * @throws ForbiddenException
105
     */
106 9
    public function checkPrivilege()
107
    {
108 9
        if ($privilege = $this->getMeta()->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->getMeta()->getMethod()
123
            && !in_array(Request::getMethod(), $this->getMeta()->getMethod())) {
124
            throw new NotAllowedException(implode(',', $this->getMeta()->getMethod()));
125
        }
126 8
    }
127
128
    /**
129
     * Check `Accept`
130
     *
131
     * @throws NotAcceptableException
132
     */
133 9
    public function checkAccept()
134
    {
135
        // all ok for CLI
136 9
        if (PHP_SAPI === 'cli') {
137 9
            return;
138
        }
139
140
        $allowAccept = $this->getMeta()->getAccept();
141
142
        // some controllers hasn't @accept tag
143
        if (!$allowAccept) {
144
            // but by default allow just HTML output
145
            $allowAccept = [Request::TYPE_HTML, Request::TYPE_ANY];
146
        }
147
148
        // get Accept with high priority
149
        $accept = Request::getAccept($allowAccept);
150
151
        // some controllers allow any type (*/*)
152
        // and client doesn't send Accept header
153
        if (in_array(Request::TYPE_ANY, $allowAccept) && !$accept) {
154
            // all OK, controller should realize logic for response
155
            return;
156
        }
157
158
        // some controllers allow just selected types
159
        // choose MIME type by browser accept header
160
        // filtered by controller @accept
161
        // switch statement for this logic
162
        switch ($accept) {
163
            case Request::TYPE_ANY:
164
            case Request::TYPE_HTML:
165
                // HTML response with layout
166
                break;
167
            case Request::TYPE_JSON:
168
                // JSON response
169
                $this->template = null;
170
                break;
171
            default:
172
                throw new NotAcceptableException;
173
        }
174
    }
175
176
    /**
177
     * __invoke
178
     *
179
     * @param array $params
180
     * @return Data
181
     * @throws ControllerException
182
     */
183 8
    public function run(array $params = [])
184
    {
185
        // initial variables for use inside controller
186 8
        $module = $this->module;
187 8
        $controller = $this->controller;
188
189 8
        $cacheKey = "data.$module.$controller." . md5(http_build_query($params));
190
191 8
        $cacheTime = $this->getMeta()->getCache();
192
193 8
        if ($cacheTime && $cached = Cache::get($cacheKey)) {
194
            $this->data = $cached;
195
            return $cached;
196
        }
197
198
        /**
199
         * @var \closure $controllerClosure
200
         */
201 8
        $controllerClosure = include $this->getFile();
202
203 8
        if (!is_callable($controllerClosure)) {
204
            throw new ControllerException("Controller is not callable '{$module}/{$controller}'");
205
        }
206
207
        // process params
208 8
        $params = $this->getMeta()->params($params);
209
210
        // call Closure or Controller
211 8
        $result = $controllerClosure(...$params);
212
213
        // switch statement for result of Closure run
214
        switch (true) {
215 6
            case ($result === false):
216
                // return "false" is equal to disable view and layout
217
                $this->disableLayout();
218
                $this->disableView();
219
                break;
220 6
            case is_string($result):
221
                // return string variable is equal to change view template
222
                $this->template = $result;
223
                break;
224 6
            case is_array($result):
225
                // return associative array is equal to setup view data
226 3
                $this->getData()->setFromArray($result);
227 3
                break;
228
            case ($result instanceof Controller):
229
                $this->getData()->setFromArray($result->getData()->toArray());
230
                break;
231
        }
232
233 6
        if ($cacheTime) {
234
            Cache::set(
235
                $cacheKey,
236
                $this->getData(),
237
                $cacheTime,
238
                ['system', 'data', Cache::prepare("$module.$controller")]
239
            );
240
        }
241
242 6
        return $this->getData();
243
    }
244
245
    /**
246
     * Setup controller file
247
     *
248
     * @return void
249
     * @throws ControllerException
250
     */
251 650
    protected function setFile()
252
    {
253 650
        $path = Application::getInstance()->getPath();
254 650
        $file = "$path/modules/{$this->module}/controllers/{$this->controller}.php";
255
256 650
        if (!file_exists($file)) {
257 3
            throw new ControllerException("Controller file not found '{$this->module}/{$this->controller}'", 404);
258
        }
259
260 650
        $this->file = $file;
261 650
    }
262
263
    /**
264
     * Get controller file path
265
     * @return string
266
     */
267 650
    protected function getFile() // : string
268
    {
269 650
        if (!$this->file) {
270 650
            $this->setFile();
271
        }
272 650
        return $this->file;
273
    }
274
275
    /**
276
     * Retrieve reflection for anonymous function
277
     * @return void
278
     * @throws \Bluz\Common\Exception\ComponentException
279
     */
280 650
    protected function setMeta()
281
    {
282
        // cache for reflection data
283 650
        $cacheKey = "meta.{$this->module}.{$this->controller}";
284
285 650
        if (!$meta = Cache::get($cacheKey)) {
286 650
            $meta = new Meta($this->getFile());
287 650
            $meta->process();
288
289 650
            Cache::set(
290
                $cacheKey,
291
                $meta,
292 650
                Cache::TTL_NO_EXPIRY,
293 650
                ['system', 'meta', Cache::prepare($this->module . '.' . $this->controller)]
294
            );
295
        }
296 650
        $this->meta = $meta;
297 650
    }
298
    
299
    /**
300
     * Get meta information
301
     * @return Meta
302
     */
303 650
    public function getMeta()
304
    {
305 650
        if (!$this->meta) {
306 650
            $this->setMeta();
307
        }
308 650
        return $this->meta;
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