Completed
Push — master ( 296864...eea667 )
by Anton
9s
created

Application::initConfig()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5.583

Importance

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