Completed
Branch master (495df4)
by Anton
01:49
created

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