Completed
Push — master ( 308159...3323b4 )
by Anton
13s
created

Bootstrap::preProcess()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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