Completed
Pull Request — master (#374)
by Anton
08:00
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 630
    public function getPath()
84
    {
85 630
        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 630
        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 Layout Flag
109
     *
110
     * @param  bool|null $flag
111
     * @return bool
112
     */
113 628
    public function useLayout($flag = null)
114
    {
115 628
        if (is_bool($flag)) {
116 628
            $this->layoutFlag = $flag;
117
        }
118
        
119 628
        return $this->layoutFlag;
120
    }
121
122
    /**
123
     * Initialize process
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
            // setup configuration for current environment
141 1
            if ($debug = Config::getData('debug')) {
142
                $this->debugFlag = (bool) $debug;
143
            }
144
145
            // initial php settings
146 1
            if ($ini = Config::getData('php')) {
147
                foreach ($ini as $key => $value) {
148
                    $result = ini_set($key, $value);
149
                    Logger::info('app:init:php:'.$key.':'.($result?:'---'));
150
                }
151
            }
152
153
            // init session, start inside class
154 1
            Session::getInstance();
155
156
            // init Messages
157 1
            Messages::getInstance();
158
159
            // init Translator
160 1
            Translator::getInstance();
161
162
            // init request
163 1
            $this->initRequest();
164
165
            // init response
166 1
            $this->initResponse();
167
168
            // init router
169 1
            $this->initRouter();
170
        } catch (\Exception $e) {
171
            throw new ApplicationException("Application can't be loaded: " . $e->getMessage());
172
        }
173 1
    }
174
175
    /**
176
     * Initial Request instance
177
     *
178
     * @return void
179
     */
180 1
    protected function initRequest()
181
    {
182 1
        $request = RequestFactory::fromGlobals();
183
184 1
        Request::setInstance($request);
185 1
    }
186
187
    /**
188
     * Initial Response instance
189
     *
190
     * @return void
191
     */
192 1
    protected function initResponse()
193
    {
194 1
        $response = new ResponseInstance();
195
196 1
        Response::setInstance($response);
197 1
    }
198
199
    /**
200
     * Initial Router instance
201
     *
202
     * @return void
203
     */
204 628
    protected function initRouter()
205
    {
206 628
        $router = new \Bluz\Router\Router();
207 628
        $router->setOptions(Config::getData('router'));
208
209 628
        Router::setInstance($router);
210 628
    }
211
212
    /**
213
     * Get Response instance
214
     *
215
     * @return \Bluz\Response\Response
216
     */
217 1
    public function getResponse()
218
    {
219 1
        return Response::getInstance();
220
    }
221
222
    /**
223
     * Get Request instance
224
     *
225
     * @return \Zend\Diactoros\ServerRequest
226
     */
227 1
    public function getRequest()
228
    {
229 1
        return Request::getInstance();
230
    }
231
232
    /**
233
     * Run application
234
     *
235
     * @return void
236
     */
237
    public function run()
238
    {
239
        $this->process();
240
        $this->render();
241
        $this->end();
242
    }
243
244
    /**
245
     * Process application
246
     *
247
     * Note:
248
     * - Why you don't use "X-" prefix for custom headers?
249
     * - Because it deprecated ({@link http://tools.ietf.org/html/rfc6648})
250
     *
251
     * @return void
252
     */
253 2
    public function process()
254
    {
255 2
        Logger::info('app:process');
256
257 2
        $this->preProcess();
258 2
        $this->doProcess();
259 2
        $this->postProcess();
260 2
    }
261
262
    /**
263
     * Pre process
264
     *
265
     * @return void
266
     * @throws ApplicationException
267
     */
268 2
    protected function preProcess()
269
    {
270 2
        Logger::info("app:process:pre");
271
272 2
        Router::process();
273
274
        // disable Layout for XmlHttpRequests
275 2
        if (Request::isXmlHttpRequest()) {
276
            $this->layoutFlag = false;
277
        }
278
279
        // switch to JSON response based on Accept header
280 2
        if (Request::getAccept([Request::TYPE_HTML, Request::TYPE_JSON]) == Request::TYPE_JSON) {
281
            $this->layoutFlag = false;
282
            Response::switchType('JSON');
283
        }
284 2
    }
285
286
    /**
287
     * Do process
288
     *
289
     * @return void
290
     */
291 2
    protected function doProcess()
292
    {
293 2
        Logger::info("app:process:do");
294
295 2
        $module = Request::getModule();
296 2
        $controller = Request::getController();
297 2
        $params = Request::getParams();
298
299
        // try to dispatch controller
300
        try {
301
            // dispatch controller
302 2
            $result = $this->dispatch($module, $controller, $params);
303 1
        } catch (ForbiddenException $e) {
304
            $result = $this->forbidden($e);
305 1
        } catch (RedirectException $e) {
306
            // redirect to URL
307
            $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...
308 1
        } catch (\Exception $e) {
309 1
            $result = $this->error($e);
310
        }
311
312
        // setup layout, if needed
313 2
        if ($this->useLayout()) {
314
            // render view to layout
315
            // needed for headScript and headStyle helpers
316 2
            Layout::setContent($result->render());
317 2
            Response::setBody(Layout::getInstance());
318
        } else {
319
            Response::setBody($result);
320
        }
321 2
    }
322
323
    /**
324
     * Post process
325
     *
326
     * @return void
327
     */
328 2
    protected function postProcess()
329
    {
330 2
        Logger::info("app:process:post");
331 2
    }
332
333
    /**
334
     * Dispatch controller with params
335
     *
336
     * Call dispatch from any \Bluz\Package
337
     *     Application::getInstance()->dispatch($module, $controller, array $params);
338
     *
339
     * @param  string $module
340
     * @param  string $controller
341
     * @param  array  $params
342
     * @return Controller
343
     * @throws ApplicationException
344
     */
345 5
    public function dispatch($module, $controller, $params = [])
346
    {
347 5
        Logger::info("app:dispatch: " . $module . '/' . $controller);
348
349 5
        $this->preDispatch($module, $controller, $params);
350 5
        $result = $this->doDispatch($module, $controller, $params);
351 4
        $this->postDispatch($module, $controller, $params);
352
353 4
        return $result;
354
    }
355
356
    /**
357
     * Pre dispatch mount point
358
     *
359
     * @param  string $module
360
     * @param  string $controller
361
     * @param  array  $params
362
     * @return void
363
     */
364 5
    protected function preDispatch($module, $controller, $params = [])
365
    {
366 5
        Logger::info("---:dispatch:pre: " . $module . '/' . $controller);
367 5
    }
368
369
    /**
370
     * Do dispatch
371
     *
372
     * @param  string $module
373
     * @param  string $controller
374
     * @param  array  $params
375
     * @return Controller
376
     */
377 5
    protected function doDispatch($module, $controller, $params = [])
378
    {
379
        // @TODO: try to find custom controller class
380
381
        // create controller controller
382 5
        $controllerInstance = new Controller($module, $controller);
383
384
        // check HTTP Accept header
385 5
        $controllerInstance->checkAccept();
386
        // check HTTP method
387 5
        $controllerInstance->checkMethod();
388
        // check ACL privileges
389 4
        $controllerInstance->checkPrivilege();
390
391
        // run controller
392 4
        $controllerInstance->run($params);
393
394 4
        return $controllerInstance;
395
    }
396
397
    /**
398
     * Post dispatch mount point
399
     *
400
     * @param  string $module
401
     * @param  string $controller
402
     * @param  array  $params
403
     * @return void
404
     */
405 4
    protected function postDispatch($module, $controller, $params = [])
406
    {
407 4
        Logger::info("---:dispatch:post: " . $module . '/' . $controller);
408 4
    }
409
410
    /**
411
     * Render, is send Response
412
     *
413
     * @return void
414
     */
415
    public function render()
416
    {
417
        Logger::info('app:render');
418
419
        Response::send();
420
    }
421
422
    /**
423
     * Finally method
424
     *
425
     * @return void
426
     */
427
    public function end()
428
    {
429
        Logger::info('app:end');
430
    }
431
}
432