Completed
Pull Request — master (#289)
by Anton
11:50
created

Bootstrap::sendErrors()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 9
ccs 0
cts 0
cp 0
crap 12
rs 9.6666
c 0
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
namespace Application;
11
12
use Bluz\Application\Application;
13
use Bluz\Application\Exception\ForbiddenException;
14
use Bluz\Auth\AuthException;
15
use Bluz\Proxy\Auth as AuthProxy;
16
use Bluz\Proxy\Layout;
17
use Bluz\Proxy\Logger;
18
use Bluz\Proxy\Messages;
19
use Bluz\Proxy\Request;
20
use Bluz\Proxy\Response;
21
use Bluz\Proxy\Router;
22
use Bluz\Proxy\Session;
23
use Bluz\Proxy\Translator;
24
25
/**
26
 * Bootstrap
27
 *
28
 * @category Application
29
 * @package  Bootstrap
30
 *
31
 * @author   Anton Shevchuk
32
 * @created  20.07.11 17:38
33
 */
34
class Bootstrap extends Application
35
{
36
    /**
37
     * {@inheritdoc}
38
     *
39
     * @param string $module
40
     * @param string $controller
41
     * @param array $params
42
     * @return void
43
     */
44 37
    protected function preDispatch($module, $controller, $params = array())
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...
45
    {
46
        // example of setup default title
47 37
        Layout::title("Bluz Skeleton");
48
49
        // apply "remember me" function
50 37
        if (!AuthProxy::getIdentity()) {
51 11
            if ($token = Request::getHeader('Bluz-Token')) {
52
                Auth\Table::getInstance()->authenticateToken($token);
53 11
            } elseif (!empty($_COOKIE['rToken']) && !empty($_COOKIE['rId'])) {
54
                // try to login
55
                try {
56
                    Auth\Table::getInstance()->authenticateCookie($_COOKIE['rId'], $_COOKIE['rToken']);
57
                } catch (AuthException $e) {
58
                    $this->getResponse()->setCookie('rId', '', 1, '/');
59
                    $this->getResponse()->setCookie('rToken', '', 1, '/');
60
                }
61
            }
62
        }
63
        parent::preDispatch($module, $controller, $params);
64 37
    }
65 37
66
    /**
67
     * {@inheritdoc}
68
     *
69
     * @param string $module
70
     * @param string $controller
71
     * @param array $params
72
     * @return void
73
     */
74
    protected function postDispatch($module, $controller, $params = array())
75 31
    {
76
        parent::postDispatch($module, $controller, $params);
77 31
    }
78 31
79
    /**
80
     * Denied access
81
     * @param ForbiddenException $exception
82
     * @return \Bluz\Controller\Controller|null
83
     */
84
    public function forbidden(ForbiddenException $exception)
85 2
    {
86
        // for AJAX and API calls (over JSON)
87 2
        $jsonOrApi = Request::isXmlHttpRequest()
88 2
            || (Request::getAccept([Request::TYPE_HTML, Request::TYPE_JSON]) == Request::TYPE_JSON);
89
90
        // for guest, for requests
91
        if (!AuthProxy::getIdentity() && !$jsonOrApi) {
92
            // save URL to session and redirect make sense if presentation is null
93
            Session::set('rollback', Request::getUri()->__toString());
94 2
            // add error notice
95 2
            Messages::addError('You don\'t have permissions, please sign in');
96
            // redirect to Sign In page
97
            $url = Router::getUrl('users', 'signin');
98 2
            return $this->redirect($url);
99
        }
100
        return $this->error($exception);
101
    }
102
103
    /**
104
     * Render with debug headers
105
     * @return void
106
     */
107 2
    public function render()
108
    {
109
        Logger::info('app:render');
110
        Logger::info('app:files:' . count(get_included_files()));
111
112
        if ($this->isDebug() && !headers_sent()) {
113
            $this->sendInfoHeaders();
114
        }
115
116
        parent::render();
117
    }
118
119
    /**
120
     * Finish it
121
     * @return void
122
     */
123
    public function end()
124
    {
125
        if ($errors = Logger::get('error')) {
126
            $this->sendErrors($errors);
127
        }
128
    }
129
130
    /**
131
     * Send information headers
132
     *
133
     * @return void
134
     */
135
    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...
136
    {
137
        $debugString = sprintf(
138
            '%fsec; %skb',
139
            microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'],
140
            ceil((memory_get_usage()/1024))
141
        );
142
        $debugString .= '; '. Request::getModule() .'/'. Request::getController();
143
144
        Response::setHeader('Bluz-Debug', $debugString);
145
146
        if ($info = Logger::get('info')) {
147
            Response::setHeader('Bluz-Bar', json_encode($info));
148
        } else {
149
            Response::setHeader('Bluz-Bar', '{"!":"Logger is disabled"}');
150
        }
151
    }
152
153
    /**
154
     * sendErrorBody
155
     *
156
     * @return void
157
     */
158
    protected function sendErrors($errors)
159
    {
160
        foreach ($errors as $message) {
161
            errorLog(new \ErrorException($message, 0, E_USER_ERROR));
162
            if ($this->isDebug()) {
163
                echo "<div class='container alert alert-danger' role='alert'>$message</div>";
164
            }
165
        }
166
    }
167
}
168