Completed
Pull Request — master (#389)
by Anton
05:06
created

Application::getResponse()   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
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link https://github.com/bluzphp/framework
7
 */
8
9
/**
10
 * @namespace
11
 */
12
namespace Bluz\Application;
13
14
use Bluz\Application\Exception\ApplicationException;
15
use Bluz\Application\Exception\ForbiddenException;
16
use Bluz\Application\Exception\RedirectException;
17
use Bluz\Common;
18
use Bluz\Controller\Controller;
19
use Bluz\Proxy\Config;
20
use Bluz\Proxy\Layout;
21
use Bluz\Proxy\Logger;
22
use Bluz\Proxy\Messages;
23
use Bluz\Proxy\Request;
24
use Bluz\Proxy\Response;
25
use Bluz\Proxy\Router;
26
use Bluz\Proxy\Session;
27
use Bluz\Proxy\Translator;
28
use Bluz\Request\RequestFactory;
29
use Bluz\Response\Response as ResponseInstance;
30
31
/**
32
 * Application
33
 *
34
 * @package  Bluz\Application
35
 * @link     https://github.com/bluzphp/framework/wiki/Application
36
 * @author   Anton Shevchuk
37
 * @created  06.07.11 16:25
38
 *
39
 * @method Controller error(\Exception $exception)
40
 * @method Controller forbidden(ForbiddenException $exception)
41
 * @method null redirect(string $url)
42
 */
43
class Application
44
{
45
    use Common\Helper;
46
    use Common\Singleton;
47
48
    /**
49
     * @var string Environment name
50
     */
51
    protected $environment = 'production';
52
53
    /**
54
     * @var string Application path
55
     */
56
    protected $path;
57
58
    /**
59
     * @var bool Debug application flag
60
     */
61
    protected $debugFlag = false;
62
63
    /**
64
     * @var bool Layout usage flag
65
     */
66
    protected $layoutFlag = true;
67
68
    /**
69
     * Get application environment
70
     *
71
     * @return string
72
     */
73
    public function getEnvironment()
74
    {
75
        return $this->environment;
76
    }
77
78
    /**
79
     * Get path to Application
80
     *
81
     * @return string
82
     */
83 637
    public function getPath()
84
    {
85 637
        if (!$this->path) {
86
            if (defined('PATH_APPLICATION')) {
87
                $this->path = PATH_APPLICATION;
88
            } else {
89
                $reflection = new \ReflectionClass($this);
90
                // 3 level up
91
                $this->path = dirname(dirname(dirname($reflection->getFileName())));
92
            }
93
        }
94 637
        return $this->path;
95
    }
96
97
    /**
98
     * Return Debug flag
99
     *
100
     * @return bool
101
     */
102 2
    public function isDebug()
103
    {
104 2
        return $this->debugFlag;
105
    }
106
107
    /**
108
     * Return/setup Layout Flag
109
     *
110
     * @param  bool|null $flag
111
     * @return bool
112
     */
113 635
    public function useLayout($flag = null)
114
    {
115 635
        if (is_bool($flag)) {
116 635
            $this->layoutFlag = $flag;
117
        }
118
        
119 635
        return $this->layoutFlag;
120
    }
121
122
    /**
123
     * Initialize system packages
124
     *
125
     * @param  string $environment
126
     * @throws ApplicationException
127
     * @return void
128
     */
129 1
    public function init($environment = 'production')
130
    {
131 1
        $this->environment = $environment;
132
133
        try {
134
            // first log message
135 1
            Logger::info('app:init');
136
137
            // initial default helper path
138 1
            $this->addHelperPath(dirname(__FILE__) . '/Helper/');
139
140
            // init Config
141 1
            $this->initConfig();
142
143
            // init Session, start inside class (if needed)
144 1
            Session::getInstance();
145
146
            // init Messages
147 1
            Messages::getInstance();
148
149
            // init Translator
150 1
            Translator::getInstance();
151
152
            // init Request
153 1
            $this->initRequest();
154
155
            // init Response
156 1
            $this->initResponse();
157
158
            // init Router
159 1
            $this->initRouter();
160
        } catch (\Exception $e) {
161
            throw new ApplicationException("Application can't be loaded: " . $e->getMessage());
162
        }
163 1
    }
164
165
    /**
166
     * Initial Request instance
167
     *
168
     * @return void
169
     */
170 1
    protected function initConfig()
171
    {
172 1
        Config::getInstance();
173
174
        // setup configuration for current environment
175 1
        if ($debug = Config::getData('debug')) {
176
            $this->debugFlag = (bool) $debug;
177
        }
178
179
        // initial php settings
180 1
        if ($ini = Config::getData('php')) {
181
            foreach ($ini as $key => $value) {
182
                $result = ini_set($key, $value);
183
                Logger::info('app:init:php:'.$key.':'.($result?:'---'));
184
            }
185
        }
186 1
    }
187
188
    /**
189
     * Initial Request instance
190
     *
191
     * @return void
192
     */
193 1
    protected function initRequest()
194
    {
195 1
        $request = RequestFactory::fromGlobals();
196
197 1
        Request::setInstance($request);
198 1
    }
199
200
    /**
201
     * Initial Response instance
202
     *
203
     * @return void
204
     */
205 1
    protected function initResponse()
206
    {
207 1
        $response = new ResponseInstance();
208
209 1
        Response::setInstance($response);
210 1
    }
211
212
    /**
213
     * Initial Router instance
214
     *
215
     * @return void
216
     */
217 635
    protected function initRouter()
218
    {
219 635
        $router = new \Bluz\Router\Router();
220 635
        $router->setOptions(Config::getData('router'));
221
222 635
        Router::setInstance($router);
223 635
    }
224
225
    /**
226
     * Get Response instance
227
     *
228
     * @return \Bluz\Response\Response
229
     */
230 1
    public function getResponse()
231
    {
232 1
        return Response::getInstance();
233
    }
234
235
    /**
236
     * Get Request instance
237
     *
238
     * @return \Zend\Diactoros\ServerRequest
239
     */
240 1
    public function getRequest()
241
    {
242 1
        return Request::getInstance();
243
    }
244
245
    /**
246
     * Run application
247
     *
248
     * @return void
249
     */
250
    public function run()
251
    {
252
        $this->process();
253
        $this->render();
254
        $this->end();
255
    }
256
257
    /**
258
     * Process application
259
     *
260
     * Note:
261
     * - Why you don't use "X-" prefix for custom headers?
262
     * - Because it deprecated ({@link http://tools.ietf.org/html/rfc6648})
263
     *
264
     * @return void
265
     */
266 6
    public function process()
267
    {
268 6
        $this->preProcess();
269 6
        $this->doProcess();
270 6
        $this->postProcess();
271 6
    }
272
273
    /**
274
     * Extension point: pre process
275
     *
276
     * - Router processing
277
     * - Analyse request headers
278
     *
279
     * @return void
280
     * @throws ApplicationException
281
     */
282 6
    protected function preProcess()
283
    {
284 6
        Router::process();
285
286
        // disable Layout for XmlHttpRequests
287 6
        if (Request::isXmlHttpRequest()) {
288 1
            $this->layoutFlag = false;
289
        }
290
291
        // switch to JSON response based on Accept header
292 6
        if (Request::getAccept([Request::TYPE_HTML, Request::TYPE_JSON]) == Request::TYPE_JSON) {
293
            $this->layoutFlag = false;
294
            Response::switchType('JSON');
295
        }
296 6
    }
297
298
    /**
299
     * Do process
300
     *
301
     * - Dispatch controller
302
     * - Exceptions handling
303
     * - Setup layout
304
     * - Setup response body
305
     *
306
     * @return void
307
     */
308 6
    protected function doProcess()
309
    {
310 6
        $module = Request::getModule();
311 6
        $controller = Request::getController();
312 6
        $params = Request::getParams();
313
314
        // try to dispatch controller
315
        try {
316
            // dispatch controller
317 6
            $result = $this->dispatch($module, $controller, $params);
318 5
        } catch (ForbiddenException $e) {
319 1
            $result = $this->forbidden($e);
320 4
        } catch (RedirectException $e) {
321
            // redirect to URL
322 2
            $result = $this->redirect($e->getUrl());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $result is correct as $this->redirect($e->getUrl()) (which targets Bluz\Application\Application::redirect()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
323 2
        } catch (\Exception $e) {
324 2
            $result = $this->error($e);
325
        }
326
327
        // setup layout, if needed
328 6
        if ($this->useLayout()) {
329
            // render view to layout
330
            // needed for headScript and headStyle helpers
331 2
            Layout::setContent($result->render());
332 2
            Response::setBody(Layout::getInstance());
333
        } else {
334 4
            Response::setBody($result);
335
        }
336 6
    }
337
338
    /**
339
     * Extension point: post process
340
     *
341
     * @return void
342
     */
343 6
    protected function postProcess()
344
    {
345
        // nothing
346 6
    }
347
348
    /**
349
     * Dispatch controller with params
350
     *
351
     * Call dispatch from any \Bluz\Package
352
     *     Application::getInstance()->dispatch($module, $controller, array $params);
353
     *
354
     * @param  string $module
355
     * @param  string $controller
356
     * @param  array  $params
357
     * @return Controller
358
     * @throws ApplicationException
359
     */
360 9
    public function dispatch($module, $controller, $params = [])
361
    {
362 9
        $this->preDispatch($module, $controller, $params);
363 9
        $result = $this->doDispatch($module, $controller, $params);
364 6
        $this->postDispatch($module, $controller, $params);
365
366 6
        return $result;
367
    }
368
369
    /**
370
     * Extension point: pre dispatch
371
     *
372
     * @param  string $module
373
     * @param  string $controller
374
     * @param  array  $params
375
     * @return void
376
     */
377 9
    protected function preDispatch($module, $controller, $params = [])
378
    {
379 9
        Logger::info("app:dispatch:pre: " . $module . '/' . $controller);
380 9
    }
381
382
    /**
383
     * Do dispatch
384
     *
385
     * @param  string $module
386
     * @param  string $controller
387
     * @param  array  $params
388
     * @return Controller
389
     */
390 9
    protected function doDispatch($module, $controller, $params = [])
391
    {
392
        // @TODO: try to find custom controller class
393
394
        // create controller controller
395 9
        $controllerInstance = new Controller($module, $controller);
396
397
        // check HTTP Accept header
398 9
        $controllerInstance->checkAccept();
399
        // check HTTP method
400 9
        $controllerInstance->checkMethod();
401
        // check ACL privileges
402 8
        $controllerInstance->checkPrivilege();
403
404
        // run controller
405 8
        $controllerInstance->run($params);
406
407 6
        return $controllerInstance;
408
    }
409
410
    /**
411
     * Extension point: post dispatch
412
     *
413
     * @param  string $module
414
     * @param  string $controller
415
     * @param  array  $params
416
     * @return void
417
     */
418 6
    protected function postDispatch($module, $controller, $params = [])
419
    {
420 6
        Logger::info("<<<:dispatch:post: " . $module . '/' . $controller);
421 6
    }
422
423
    /**
424
     * Render, is send Response
425
     *
426
     * @return void
427
     */
428
    public function render()
429
    {
430
        Response::send();
431
    }
432
433
    /**
434
     * Extension point: finally method
435
     *
436
     * @return void
437
     */
438
    public function end()
439
    {
440
        // nothing
441
    }
442
}
443