Completed
Push — master ( ffb215...f806ab )
by Anton
11s
created

Application::process()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 1
rs 9.4285
c 1
b 0
f 0
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
 * @method null reload()
43
 */
44
class Application
45
{
46
    use Common\Helper;
47
    use Common\Singleton;
48
49
    /**
50
     * @var string Environment name
51
     */
52
    protected $environment = 'production';
53
54
    /**
55
     * @var string Application path
56
     */
57
    protected $path;
58
59
    /**
60
     * @var bool Debug application flag
61
     */
62
    protected $debugFlag = false;
63
64
    /**
65
     * @var bool Layout usage flag
66
     */
67
    protected $layoutFlag = true;
68
69
    /**
70
     * Get application environment
71
     *
72
     * @return string
73
     */
74
    public function getEnvironment()
75
    {
76
        return $this->environment;
77
    }
78
79
    /**
80
     * Get path to Application
81
     *
82
     * @return string
83
     */
84 632
    public function getPath()
85
    {
86 632
        if (!$this->path) {
87
            if (defined('PATH_APPLICATION')) {
88
                $this->path = PATH_APPLICATION;
89
            } else {
90
                $reflection = new \ReflectionClass($this);
91
                // 3 level up
92
                $this->path = dirname(dirname(dirname($reflection->getFileName())));
93
            }
94
        }
95 632
        return $this->path;
96
    }
97
98
    /**
99
     * Return Debug flag
100
     *
101
     * @return bool
102
     */
103 5
    public function isDebug()
104
    {
105 5
        return $this->debugFlag;
106
    }
107
108
    /**
109
     * Return Layout Flag
110
     *
111
     * @param  bool|null $flag
112
     * @return bool
113
     */
114 630
    public function useLayout($flag = null)
115
    {
116 630
        if (is_bool($flag)) {
117 630
            $this->layoutFlag = $flag;
118
        }
119
        
120 630
        return $this->layoutFlag;
121
    }
122
123
    /**
124
     * Initialize process
125
     *
126
     * @param  string $environment
127
     * @throws ApplicationException
128
     * @return void
129
     */
130 1
    public function init($environment = 'production')
131
    {
132 1
        $this->environment = $environment;
133
134
        try {
135
            // first log message
136 1
            Logger::info('app:init');
137
138
            // initial default helper path
139 1
            $this->addHelperPath(dirname(__FILE__) . '/Helper/');
140
141
            // setup configuration for current environment
142 1
            if ($debug = Config::getData('debug')) {
143
                $this->debugFlag = (bool) $debug;
144
            }
145
146
            // initial php settings
147 1
            if ($ini = Config::getData('php')) {
148
                foreach ($ini as $key => $value) {
149
                    $result = ini_set($key, $value);
150
                    Logger::info('app:init:php:'.$key.':'.($result?:'---'));
151
                }
152
            }
153
154
            // init session, start inside class
155 1
            Session::getInstance();
156
157
            // init Messages
158 1
            Messages::getInstance();
159
160
            // init Translator
161 1
            Translator::getInstance();
162
163
            // init request
164 1
            $this->initRequest();
165
166
            // init response
167 1
            $this->initResponse();
168
169
            // init router
170 1
            $this->initRouter();
171
        } catch (\Exception $e) {
172
            throw new ApplicationException("Application can't be loaded: " . $e->getMessage());
173
        }
174 1
    }
175
176
    /**
177
     * Initial Request instance
178
     *
179
     * @return void
180
     */
181 1
    protected function initRequest()
182
    {
183 1
        $request = RequestFactory::fromGlobals();
184
185 1
        Request::setInstance($request);
186 1
    }
187
188
    /**
189
     * Initial Response instance
190
     *
191
     * @return void
192
     */
193 1
    protected function initResponse()
194
    {
195 1
        $response = new ResponseInstance();
196
197 1
        Response::setInstance($response);
198 1
    }
199
200
    /**
201
     * Initial Router instance
202
     *
203
     * @return void
204
     */
205 630
    protected function initRouter()
206
    {
207 630
        $router = new \Bluz\Router\Router();
208 630
        $router->setOptions(Config::getData('router'));
209
210 630
        Router::setInstance($router);
211 630
    }
212
213
    /**
214
     * Get Response instance
215
     *
216
     * @return \Bluz\Response\Response
217
     */
218 1
    public function getResponse()
219
    {
220 1
        return Response::getInstance();
221
    }
222
223
    /**
224
     * Get Request instance
225
     *
226
     * @return \Zend\Diactoros\ServerRequest
227
     */
228 1
    public function getRequest()
229
    {
230 1
        return Request::getInstance();
231
    }
232
233
    /**
234
     * Run application
235
     *
236
     * @return void
237
     */
238
    public function run()
239
    {
240
        $this->process();
241
        $this->render();
242
        $this->finish();
243
    }
244
245
    /**
246
     * Process application
247
     *
248
     * Note:
249
     * - Why you don't use "X-" prefix for custom headers?
250
     * - Because it deprecated ({@link http://tools.ietf.org/html/rfc6648})
251
     *
252
     * @return void
253
     */
254 2
    public function process()
255
    {
256 2
        Logger::info('app:process');
257
258 2
        $this->preProcess();
259 2
        $this->doProcess();
260 2
        $this->postProcess();
261 2
    }
262
263
    /**
264
     * Pre process
265
     *
266
     * @return void
267
     * @throws ApplicationException
268
     */
269 2
    protected function preProcess()
270
    {
271 2
        Logger::info("app:process:pre");
272
273 2
        Router::process();
274
275
        // disable Layout for XmlHttpRequests
276 2
        if (Request::isXmlHttpRequest()) {
277
            $this->layoutFlag = false;
278
        }
279
280
        // switch to JSON response based on Accept header
281 2
        if (Request::getAccept([Request::TYPE_HTML, Request::TYPE_JSON]) == Request::TYPE_JSON) {
282
            $this->layoutFlag = false;
283
            Response::switchType('JSON');
284
        }
285 2
    }
286
287
    /**
288
     * Do process
289
     *
290
     * @return void
291
     */
292 2
    protected function doProcess()
293
    {
294 2
        Logger::info("app:process:do");
295
296 2
        $module = Request::getModule();
297 2
        $controller = Request::getController();
298 2
        $params = Request::getParams();
299
300
        // try to dispatch controller
301
        try {
302
            // dispatch controller
303 2
            $result = $this->dispatch($module, $controller, $params);
304 1
        } catch (ForbiddenException $e) {
305
            $result = $this->forbidden($e);
306 1
        } catch (RedirectException $e) {
307
            // redirect to URL
308
            $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...
309 1
        } catch (\Exception $e) {
310 1
            $result = $this->error($e);
311
        }
312
313
        // setup layout, if needed
314 2
        if ($this->useLayout()) {
315
            // render view to layout
316
            // needed for headScript and headStyle helpers
317 2
            Layout::setContent($result->render());
318 2
            Response::setBody(Layout::getInstance());
319
        } else {
320
            Response::setBody($result);
321
        }
322 2
    }
323
324
    /**
325
     * Post process
326
     *
327
     * @return void
328
     */
329 2
    protected function postProcess()
330
    {
331 2
        Logger::info("app:process:post");
332 2
    }
333
334
    /**
335
     * Dispatch controller with params
336
     *
337
     * Call dispatch from any \Bluz\Package
338
     *     Application::getInstance()->dispatch($module, $controller, array $params);
339
     *
340
     * @param  string $module
341
     * @param  string $controller
342
     * @param  array  $params
343
     * @return Controller
344
     * @throws ApplicationException
345
     */
346 5
    public function dispatch($module, $controller, $params = array())
347
    {
348 5
        Logger::info("app:dispatch: " . $module . '/' . $controller);
349
350 5
        $this->preDispatch($module, $controller, $params);
351 5
        $result = $this->doDispatch($module, $controller, $params);
352 4
        $this->postDispatch($module, $controller, $params);
353
354 4
        return $result;
355
    }
356
357
    /**
358
     * Pre dispatch mount point
359
     *
360
     * @param  string $module
361
     * @param  string $controller
362
     * @param  array  $params
363
     * @return void
364
     */
365 5
    protected function preDispatch($module, $controller, $params = array())
366
    {
367 5
        Logger::info("---:dispatch:pre: " . $module . '/' . $controller);
368 5
    }
369
370
    /**
371
     * Do dispatch
372
     *
373
     * @param  string $module
374
     * @param  string $controller
375
     * @param  array  $params
376
     * @return Controller
377
     */
378 5
    protected function doDispatch($module, $controller, $params = array())
379
    {
380
        // @TODO: try to find custom controller class
381
382
        // create controller controller
383 5
        $controllerInstance = new Controller($module, $controller);
384
385
        // check HTTP Accept header
386 5
        $controllerInstance->checkAccept();
387
        // check HTTP method
388 5
        $controllerInstance->checkMethod();
389
        // check ACL privileges
390 4
        $controllerInstance->checkPrivilege();
391
392
        // run controller
393 4
        $controllerInstance->run($params);
394
395 4
        return $controllerInstance;
396
    }
397
398
    /**
399
     * Post dispatch mount point
400
     *
401
     * @param  string $module
402
     * @param  string $controller
403
     * @param  array  $params
404
     * @return void
405
     */
406 4
    protected function postDispatch($module, $controller, $params = array())
407
    {
408 4
        Logger::info("---:dispatch:post: " . $module . '/' . $controller);
409 4
    }
410
411
    /**
412
     * Render, is send Response
413
     *
414
     * @return void
415
     */
416
    public function render()
417
    {
418
        Logger::info('app:render');
419
420
        Response::send();
421
    }
422
423
    /**
424
     * Finally method
425
     *
426
     * @return void
427
     */
428
    public function finish()
429
    {
430
        Logger::info('app:finish');
431
    }
432
}
433