Completed
Push — master ( 381cdd...447693 )
by Anton
11s
created

Bootstrap::render()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 0
dl 0
loc 16
ccs 0
cts 15
cp 0
crap 30
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Bluz PHP Team
4
 * @link      https://github.com/bluzphp/skeleton
5
 */
6
7
declare(strict_types=1);
8
9
namespace Application;
10
11
use Application\Auth;
12
use Bluz\Application\Application;
13
use Bluz\Application\Exception\ForbiddenException;
14
use Bluz\Auth\AuthException;
15
use Bluz\Controller\Controller;
16
use Bluz\Proxy\Auth as AuthProxy;
17
use Bluz\Proxy\Layout;
18
use Bluz\Proxy\Logger;
19
use Bluz\Proxy\Messages;
20
use Bluz\Proxy\Request;
21
use Bluz\Proxy\Response;
22
use Bluz\Proxy\Router;
23
use Bluz\Proxy\Session;
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
0 ignored issues
show
Coding Style introduced by
Since you have declared the constructor as private, maybe you should also declare the class as final.
Loading history...
35
{
36
    /**
37
     * {@inheritdoc}
38
     *
39
     * @param Controller $controller
40
     *
41
     * @return void
42
     * @throws \Application\Exception
43
     * @throws \Bluz\Auth\AuthException
44
     * @throws \InvalidArgumentException
45
     */
46
    protected function preDispatch($controller)
47
    {
48
        // example of setup default title
49
        Layout::title('Bluz Skeleton');
50
51
        if (!AuthProxy::getIdentity() && $controller->getModule() !== Router::getErrorModule()) {
52
            if ($token = Request::getCookie('Auth-Token')) {
53
                // try to login by token from cookies
54
                try {
55
                    Auth\Provider\Cookie::authenticate($token);
56
                } catch (AuthException $e) {
57
                    $this->getResponse()->setCookie('Auth-Token', '', 1, '/');
58
                }
59
            } elseif ($token = Request::getHeader('Auth-Token')) {
60
                // try to login by token from headers
61
                Auth\Provider\Token::authenticate($token);
62
            }
63
        }
64
        parent::preDispatch($controller);
65
    }
66
67
    /**
68
     * Denied access
69
     *
70
     * @param ForbiddenException $exception
71
     *
72
     * @return \Bluz\Controller\Controller|null
73
     */
74
    public function forbidden(ForbiddenException $exception)
75
    {
76
        // for AJAX and API calls (over JSON)
77
        $jsonOrApi = Request::isXmlHttpRequest()
78
            || (Request::checkAccept([Request::TYPE_HTML, Request::TYPE_JSON]) === Request::TYPE_JSON);
79
80
        // for guest, for requests
81
        if (!$jsonOrApi && !AuthProxy::getIdentity()) {
82
            // save URL to session and redirect make sense if presentation is null
83
            Session::set('rollback', Request::getUri()->__toString());
84
            // add error notice
85
            Messages::addError('You don\'t have permissions, please sign in');
86
            // redirect to Sign In page
87
            $url = Router::getUrl('users', 'signin');
88
            return $this->redirect($url);
89
        }
90
        return $this->error($exception);
91
    }
92
93
    /**
94
     * Render with debug headers
95
     *
96
     * @return void
97
     */
98
    public function render()
99
    {
100
        Logger::info('app:render');
101
        Logger::info('app:files:' . count(get_included_files()));
102
103
        if ($this->isDebug()) {
104
            if (!headers_sent()) {
105
                $this->sendInfoHeaders();
106
            }
107
            if (ob_get_level() > 0 && ob_get_length() > 0) {
108
                Logger::error('Output has been sent previously');
109
                return;
110
            }
111
        }
112
        parent::render();
113
    }
114
115
    /**
116
     * Finish it
117
     *
118
     * @return void
119
     */
120
    public function end()
121
    {
122
        if ($errors = Logger::get('error')) {
123
            $this->sendErrors($errors);
124
        }
125
    }
126
127
    /**
128
     * Send information headers
129
     *
130
     * @return void
131
     */
132
    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...
133
    {
134
        $debugString = sprintf(
135
            '%fsec; %skb',
136
            microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'],
137
            ceil(memory_get_usage() / 1024)
138
        );
139
        $debugString .= '; ' . Request::getModule() . '/' . Request::getController();
140
141
        Response::setHeader('Bluz-Debug', $debugString);
142
143
        if ($info = Logger::get('info')) {
144
            Response::setHeader('Bluz-Bar', json_encode($info));
145
        } else {
146
            Response::setHeader('Bluz-Bar', '{"!":"Logger is disabled"}');
147
        }
148
    }
149
150
    /**
151
     * sendErrorBody
152
     *
153
     * @param  array $errors
154
     *
155
     * @return void
156
     */
157
    protected function sendErrors($errors)
158
    {
159
        foreach ($errors as $message) {
160
            errorLog(new \ErrorException($message, 0, E_USER_ERROR));
161
        }
162
    }
163
}
164