GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( cf9260...b52382 )
by
unknown
03:19
created

Output   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 324
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 144
dl 0
loc 324
rs 8.96
c 0
b 0
f 0
wmc 43

6 Methods

Rating   Name   Duplication   Size   Complexity  
A shutdownHandler() 0 7 2
B sendError() 0 57 10
C exceptionHandler() 0 63 12
A getFilePath() 0 15 5
C errorHandler() 0 94 12
A __construct() 0 6 2

How to fix   Complexity   

Complex Class

Complex classes like Output often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Output, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * This file is part of the O2System Framework package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @author         Steeve Andrian Salim
9
 * @copyright      Copyright (c) Steeve Andrian Salim
10
 */
11
12
// ------------------------------------------------------------------------
13
14
namespace O2System\Framework\Http;
15
16
// ------------------------------------------------------------------------
17
18
use O2System\Gear\Trace;
19
use O2System\Spl\Exceptions\Abstracts\AbstractException;
20
use O2System\Spl\Exceptions\ErrorException;
21
22
/**
23
 * Class Output
24
 * @package O2System\Framework\Http
25
 */
26
class Output extends \O2System\Kernel\Http\Output
27
{
28
    /**
29
     * Output::__construct
30
     */
31
    public function __construct()
32
    {
33
        parent::__construct();
34
35
        if(services()->has('csrfProtection')) {
36
            $this->addHeader('X-CSRF-TOKEN', services()->get('csrfProtection')->getToken());
37
        }
38
    }
39
40
    // ------------------------------------------------------------------------
41
42
    /**
43
     * Output::shutdownHandler
44
     *
45
     * Kernel defined shutdown handler function.
46
     *
47
     * @return void
48
     * @throws \O2System\Spl\Exceptions\ErrorException
49
     */
50
    public function shutdownHandler()
51
    {
52
        parent::shutdownHandler();
53
54
        // Execute Shutdown Service
55
        if (services()->has('shutdown')) {
56
            shutdown()->execute();
57
        }
58
59
    }
60
61
    // ------------------------------------------------------------------------
62
63
    /**
64
     * Output::getFilePath
65
     *
66
     * @param string $filename
67
     *
68
     * @return string
69
     */
70
    public function getFilePath($filename)
71
    {
72
        if (modules()) {
73
            $filePaths = modules()->getDirs('Views');
0 ignored issues
show
Bug introduced by
The method getDirs() does not exist on O2System\Framework\Conta...s\DataStructures\Module. Did you maybe mean getDir()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

73
            $filePaths = modules()->/** @scrutinizer ignore-call */ getDirs('Views');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
74
        } else {
75
            $filePaths = array_reverse($this->filePaths);
76
        }
77
78
        foreach ($filePaths as $filePath) {
79
            if (is_file($filePath . $filename . '.phtml')) {
80
                return $filePath . $filename . '.phtml';
81
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
82
            } elseif (is_file($filePath . 'errors' . DIRECTORY_SEPARATOR . $filename . '.phtml')) {
83
                return $filePath . 'errors' . DIRECTORY_SEPARATOR . $filename . '.phtml';
84
                break;
85
            }
86
        }
87
    }
88
89
    // ------------------------------------------------------------------------
90
91
    /**
92
     * Output::errorHandler
93
     *
94
     * Kernel defined error handler function.
95
     *
96
     * @param int    $errorSeverity The first parameter, errno, contains the level of the error raised, as an integer.
97
     * @param string $errorMessage  The second parameter, errstr, contains the error message, as a string.
98
     * @param string $errorFile     The third parameter is optional, errfile, which contains the filename that the error
99
     *                              was raised in, as a string.
100
     * @param string $errorLine     The fourth parameter is optional, errline, which contains the line number the error
101
     *                              was raised at, as an integer.
102
     * @param array  $errorContext  The fifth parameter is optional, errcontext, which is an array that points to the
103
     *                              active symbol table at the point the error occurred. In other words, errcontext will
104
     *                              contain an array of every variable that existed in the scope the error was triggered
105
     *                              in. User error handler must not modify error context.
106
     *
107
     * @return bool If the function returns FALSE then the normal error handler continues.
108
     * @throws ErrorException
109
     */
110
    public function errorHandler($errorSeverity, $errorMessage, $errorFile, $errorLine, $errorContext = [])
111
    {
112
        $isFatalError = (((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR) & $errorSeverity) === $errorSeverity);
113
114
        if (strpos($errorFile, 'parser') !== false) {
115
            if (function_exists('parser')) {
116
                if (services()->has('presenter')) {
117
                    $vars = presenter()->getArrayCopy();
118
                    extract($vars);
119
                }
120
121
                $errorFile = str_replace(PATH_ROOT, DIRECTORY_SEPARATOR, parser()->getSourceFilePath());
0 ignored issues
show
Bug introduced by
The constant O2System\Framework\Http\PATH_ROOT was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
122
                $error = new ErrorException($errorMessage, $errorSeverity, $errorFile, $errorLine, $errorContext);
0 ignored issues
show
Bug introduced by
$errorLine of type string is incompatible with the type integer expected by parameter $line of O2System\Spl\Exceptions\...xception::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

122
                $error = new ErrorException($errorMessage, $errorSeverity, $errorFile, /** @scrutinizer ignore-type */ $errorLine, $errorContext);
Loading history...
123
124
                $filePath = $this->getFilePath('error');
125
126
                ob_start();
127
                include $filePath;
128
                $htmlOutput = ob_get_contents();
129
                ob_end_clean();
130
131
                echo $htmlOutput;
132
133
                return true;
134
            }
135
        }
136
137
        // When the error is fatal the Kernel will throw it as an exception.
138
        if ($isFatalError) {
139
            throw new ErrorException($errorMessage, $errorSeverity, $errorLine, $errorLine, $errorContext);
140
        }
141
142
        // Should we ignore the error? We'll get the current error_reporting
143
        // level and add its bits with the severity bits to find out.
144
        if (($errorSeverity & error_reporting()) !== $errorSeverity) {
145
            return false;
146
        }
147
148
        $error = new ErrorException($errorMessage, $errorSeverity, $errorFile, $errorLine, $errorContext);
149
150
        // Logged the error
151
        if(services()->has('logger')) {
152
            logger()->error(
153
                implode(
154
                    ' ',
155
                    [
156
                        '[ ' . $error->getStringSeverity() . ' ] ',
157
                        $error->getMessage(),
158
                        $error->getFile() . ':' . $error->getLine(),
159
                    ]
160
                )
161
            );
162
        }
163
164
        // Should we display the error?
165
        if (str_ireplace(['off', 'none', 'no', 'false', 'null'], 0, ini_get('display_errors')) == 1) {
166
            if (is_ajax()) {
167
                $this->setContentType('application/json');
168
                $this->statusCode = 500;
169
                $this->reasonPhrase = 'Internal Server Error';
170
171
                $this->send(implode(
172
                    ' ',
173
                    [
174
                        '[ ' . $error->getStringSeverity() . ' ] ',
175
                        $error->getMessage(),
176
                        $error->getFile() . ':' . $error->getLine(),
177
                    ]
178
                ));
179
                exit(EXIT_ERROR);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
180
            }
181
182
            if (services()->has('presenter')) {
183
                if (presenter()->theme) {
184
                    presenter()->theme->load();
185
                }
186
187
                $vars = presenter()->getArrayCopy();
188
                extract($vars);
189
            }
190
191
            $filePath = $this->getFilePath('error');
192
193
            ob_start();
194
            include $filePath;
195
            $htmlOutput = ob_get_contents();
196
            ob_end_clean();
197
198
            if (services()->has('presenter')) {
199
                $htmlOutput = presenter()->assets->parseSourceCode($htmlOutput);
200
            }
201
202
            echo $htmlOutput;
203
            exit(EXIT_ERROR);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
204
        }
205
    }
206
207
    // ------------------------------------------------------------------------
208
209
    /**
210
     * Output::exceptionHandler
211
     *
212
     * Kernel defined exception handler function.
213
     *
214
     * @param \Exception|\Error|\O2System\Spl\Exceptions\Abstracts\AbstractException $exception Throwable exception.
215
     *
216
     * @return void
217
     */
218
    public function exceptionHandler($exception)
219
    {
220
        if (is_ajax()) {
221
            $this->statusCode = 500;
222
            $this->reasonPhrase = 'Internal Server Error';
223
224
            $this->send(implode(
225
                ' ',
226
                [
227
                    ($exception->getCode() != 0 ? '[ ' . $exception->getCode() . ']' : ''),
228
                    $exception->getMessage(),
229
                    $exception->getFile() . ':' . $exception->getLine(),
230
                ]
231
            ));
232
        } elseif ($exception instanceof AbstractException) {
233
234
            if (services()->has('presenter')) {
235
                if (presenter()->theme) {
236
                    presenter()->theme->load();
237
                }
238
239
                $vars = presenter()->getArrayCopy();
240
                extract($vars);
241
            }
242
243
            ob_start();
244
            include $this->getFilePath('exception');
245
            $htmlOutput = ob_get_contents();
246
            ob_end_clean();
247
248
            if (services()->has('presenter')) {
249
                $htmlOutput = presenter()->assets->parseSourceCode($htmlOutput);
250
            }
251
252
            echo $htmlOutput;
253
            exit(EXIT_ERROR);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
254
        } elseif ($exception instanceof \Exception || $exception instanceof \Error) {
0 ignored issues
show
introduced by
$exception is always a sub-type of Error.
Loading history...
255
256
            $exceptionClassName = get_class_name($exception);
257
            $header = language()->getLine('E_HEADER_' . $exceptionClassName);
258
            $description = language()->getLine('E_DESCRIPTION_' . $exceptionClassName);
259
            $trace = new Trace($exception->getTrace());
260
261
            if (services()->has('presenter')) {
262
                if (presenter()->theme) {
263
                    presenter()->theme->load();
264
                }
265
266
                $vars = presenter()->getArrayCopy();
267
                extract($vars);
268
            }
269
270
            ob_start();
271
            include $this->getFilePath('exception-spl');
272
            $htmlOutput = ob_get_contents();
273
            ob_end_clean();
274
275
            if (services()->has('presenter')) {
276
                $htmlOutput = presenter()->assets->parseSourceCode($htmlOutput);
277
            }
278
279
            echo $htmlOutput;
280
            exit(EXIT_ERROR);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
281
        }
282
    }
283
284
    // ------------------------------------------------------------------------
285
286
    /**
287
     * Output::sendError
288
     *
289
     * @param int               $code
290
     * @param null|array|string $vars
291
     * @param array             $headers
292
     */
293
    public function sendError($code = 204, $vars = null, $headers = [])
294
    {
295
        $languageKey = $code . '_' . error_code_string($code);
296
297
        $error = [
298
            'code'    => $code,
299
            'title'   => language()->getLine($languageKey . '_TITLE'),
300
            'message' => language()->getLine($languageKey . '_MESSAGE'),
301
        ];
302
303
        $this->statusCode = $code;
304
        $this->reasonPhrase = $error[ 'title' ];
305
306
        if (is_string($vars)) {
307
            $vars = ['message' => $vars];
308
        } elseif (is_array($vars) and empty($vars[ 'message' ])) {
309
            $vars[ 'message' ] = $error[ 'message' ];
310
        }
311
312
        if (isset($vars[ 'message' ])) {
313
            $error[ 'message' ] = $vars[ 'message' ];
314
        }
315
316
        if (is_ajax() or $this->mimeType !== 'text/html') {
317
            $this->statusCode = $code;
318
            $this->reasonPhrase = $error[ 'title' ];
319
            $this->send($vars);
320
321
            exit(EXIT_ERROR);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
322
        }
323
324
        $this->sendHeaders($headers);
325
326
        if (services()->has('presenter')) {
327
            presenter()->initialize();
328
329
            if (presenter()->theme) {
330
                presenter()->theme->load();
331
            }
332
333
            $vars = presenter()->getArrayCopy();
334
            extract($vars);
335
        }
336
337
        extract($error);
338
339
        ob_start();
340
        include $this->getFilePath('error-code');
341
        $htmlOutput = ob_get_contents();
342
        ob_end_clean();
343
344
        if (services()->has('presenter')) {
345
            $htmlOutput = presenter()->assets->parseSourceCode($htmlOutput);
346
        }
347
348
        echo $htmlOutput;
349
        exit(EXIT_ERROR);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
350
    }
351
}