Completed
Push — master ( e6e418...138234 )
by Anton
12s
created

Bootstrap::end()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
ccs 0
cts 6
cp 0
crap 6
rs 9.4285
c 1
b 0
f 0
1
<?php
2
/**
3
 * @copyright Bluz PHP Team
4
 * @link      https://github.com/bluzphp/skeleton
5
 */
6
7
/**
8
 * @namespace
9
 */
10
11
namespace Application;
12
13
use Bluz\Application\Application;
14
use Bluz\Application\Exception\ForbiddenException;
15
use Bluz\Auth\AuthException;
16
use Bluz\Controller\Controller;
17
use Bluz\Proxy\Auth as AuthProxy;
18
use Bluz\Proxy\Layout;
19
use Bluz\Proxy\Logger;
20
use Bluz\Proxy\Messages;
21
use Bluz\Proxy\Request;
22
use Bluz\Proxy\Response;
23
use Bluz\Proxy\Router;
24
use Bluz\Proxy\Session;
25
26
/**
27
 * Bootstrap
28
 *
29
 * @category Application
30
 * @package  Bootstrap
31
 *
32
 * @author   Anton Shevchuk
33
 * @created  20.07.11 17:38
34
 */
35
class Bootstrap extends Application
36
{
37
    /**
38
     * {@inheritdoc}
39
     *
40
     * @param Controller $controller
41
     *
42
     * @return void
43
     * @throws \Application\Exception
44
     * @throws \Bluz\Auth\AuthException
45
     * @throws \InvalidArgumentException
46
     */
47
    protected function preDispatch($controller)
0 ignored issues
show
Coding Style introduced by
preDispatch uses the super-global variable $_COOKIE which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
48
    {
49
        // example of setup default title
50
        Layout::title('Bluz Skeleton');
51
52
        // apply "remember me" function
53
        if (!AuthProxy::getIdentity()) {
54
            if ($token = Request::getHeader('Bluz-Token')) {
55
                Auth\Table::getInstance()->authenticateToken($token);
56
            } elseif (!empty($_COOKIE['rToken']) && !empty($_COOKIE['rId'])) {
57
                // try to login
58
                try {
59
                    Auth\Table::getInstance()->authenticateCookie($_COOKIE['rId'], $_COOKIE['rToken']);
60
                } catch (AuthException $e) {
61
                    $this->getResponse()->setCookie('rId', '', 1, '/');
62
                    $this->getResponse()->setCookie('rToken', '', 1, '/');
63
                }
64
            }
65
        }
66
        parent::preDispatch($controller);
67
    }
68
69
    /**
70
     * Denied access
71
     *
72
     * @param ForbiddenException $exception
73
     *
74
     * @return \Bluz\Controller\Controller|null
75
     */
76
    public function forbidden(ForbiddenException $exception)
77
    {
78
        // for AJAX and API calls (over JSON)
79
        $jsonOrApi = Request::isXmlHttpRequest()
80
            || (Request::checkAccept([Request::TYPE_HTML, Request::TYPE_JSON]) === Request::TYPE_JSON);
81
82
        // for guest, for requests
83
        if (!$jsonOrApi && !AuthProxy::getIdentity()) {
84
            // save URL to session and redirect make sense if presentation is null
85
            Session::set('rollback', Request::getUri()->__toString());
86
            // add error notice
87
            Messages::addError('You don\'t have permissions, please sign in');
88
            // redirect to Sign In page
89
            $url = Router::getUrl('users', 'signin');
90
            return $this->redirect($url);
91
        }
92
        return $this->error($exception);
93
    }
94
95
    /**
96
     * Render with debug headers
97
     *
98
     * @return void
99
     */
100
    public function render()
101
    {
102
        Logger::info('app:render');
103
        Logger::info('app:files:' . count(get_included_files()));
104
105
        if ($this->isDebug() && !headers_sent()) {
106
            $this->sendInfoHeaders();
107
        }
108
109
        parent::render();
110
    }
111
112
    /**
113
     * Finish it
114
     *
115
     * @return void
116
     */
117
    public function end()
118
    {
119
        if ($errors = Logger::get('error')) {
120
            $this->sendErrors($errors);
121
        }
122
    }
123
124
    /**
125
     * Send information headers
126
     *
127
     * @return void
128
     */
129
    protected function sendInfoHeaders()
0 ignored issues
show
Coding Style introduced by
sendInfoHeaders uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
130
    {
131
        $debugString = sprintf(
132
            '%fsec; %skb',
133
            microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'],
134
            ceil(memory_get_usage() / 1024)
135
        );
136
        $debugString .= '; ' . Request::getModule() . '/' . Request::getController();
137
138
        Response::setHeader('Bluz-Debug', $debugString);
139
140
        if ($info = Logger::get('info')) {
141
            Response::setHeader('Bluz-Bar', json_encode($info));
142
        } else {
143
            Response::setHeader('Bluz-Bar', '{"!":"Logger is disabled"}');
144
        }
145
    }
146
147
    /**
148
     * sendErrorBody
149
     *
150
     * @param  array $errors
151
     *
152
     * @return void
153
     */
154
    protected function sendErrors($errors)
155
    {
156
        foreach ($errors as $message) {
157
            errorLog(new \ErrorException($message, 0, E_USER_ERROR));
158
        }
159
    }
160
}
161