Exception::toArray()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 0
cts 18
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 13
nc 3
nop 1
crap 12
1
<?php
2
3
/**
4
 *
5
 * This file is part of the Apix Project.
6
 *
7
 * (c) Franck Cassedanne <franck at ouarz.net>
8
 *
9
 * @license     http://opensource.org/licenses/BSD-3-Clause  New BSD License
10
 *
11
 */
12
13
namespace Apix;
14
15
use Apix\Service;
16
17
class Exception extends \Exception
18
{
19
    const CRITICAL_ERROR_STRING = '500 Internal Server Error';
20
21
    /**
22
     *  E_RECOVERABLE_ERROR handler.
23
     *
24
     *  Use to re-throw E_RECOVERABLE_ERROR as they occur.
25
     *
26
     * @param  int             $code     The error number.
27
     * @param  string          $msg      The error message.
28
     * @param  string          $file     The filename where the error occured.
29
     * @param  int             $line     The line number where it happened.
30
     * @param  \Exception|null $previous The previous chaining Exception.
31
     * @throws \ErrorException
32
     */
33
    public static function errorHandler(
34
        $code, $msg = '', $file = __FILE__, $line = __LINE__, $previous = null
35
    ) {
36
        if (E_RECOVERABLE_ERROR == $code) {
37
            $msg = preg_replace('@to\s.*::\w+\(\)@', '', $msg, 1);
38
            // $code = 400; // Due to a client error, recoverable.
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
39
        }
40
        $code = 500; // Set as a HTTP Internal Server Error.
41
42
        if ( null !== $previous && !($previous instanceof \Exception) ) {
43
44
            Service::get('logger')->error(
45
                '{0} - {1}:{2} {3}',
46
                array($msg, $file, $line, $previous)
47
            );
48
49
            $previous = null;
50
        }
51
52
        throw new \ErrorException($msg, $code, 0, $file, $line, $previous);
53
    }
54
55
    /**
56
     * Startup exception handler.
57
     *
58
     * @param \Exception $e
59
     * @return array
60
     */
61
    public static function startupException(\Exception $e)
62
    {
63
        return self::criticalError($e, 'Startup Exception');
64
    }
65
66
    /**
67
     * Shutdown/fatal exceptions handler.
68
     *
69
     * @see criticalError
70
     * @return void
71
     * @codeCoverageIgnore
72
     */
73
    public static function shutdownHandler()
74
    {
75
        if ($e = error_get_last()) {
76
            self::criticalError($e, 'Shutdown Exception');
0 ignored issues
show
Documentation introduced by
$e is of type array, but the function expects a object<Exception>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
77
        }
78
    }
79
80
    /**
81
     * Handles critical errors (output and logging).
82
     *
83
     * @param \Exception $e
84
     * @return array
85
     */
86
    public static function criticalError(\Exception $e, $alt_msg) 
0 ignored issues
show
Coding Style introduced by
criticalError 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...
87
    {
88
        $err = array(
89
            'msg' => self::CRITICAL_ERROR_STRING,
90
            'ctx' => sprintf(
91
                        '#%d %s @ %s:%d',
92
                        $e->code,
93
                        $e->message ? $e->message : $alt_msg,
94
                        $e->file,
95
                        $e->line
96
                    )
97
        );
98
        printf('<h1>%s</h1>', $err['msg']);
99
100
        Service::get('logger')->critical('{msg} - {ctx}', $err);
101
102
        // @codeCoverageIgnoreStart
103
        // TODO: Move the following crap in the Response object...
104
        if (!defined('UNIT_TEST')) {
105
            $proto = isset($_SERVER['SERVER_PROTOCOL'])
106
                        ? $_SERVER['SERVER_PROTOCOL']
107
                        : 'HTTP/1.1';
108
            header($proto . ' ' . $err['msg'], true, 500);
109
            if(DEBUG) var_dump( $err );
0 ignored issues
show
Security Debugging Code introduced by
var_dump($err); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
110
        }
111
        // @codeCoverageIgnoreEnd
112
113
        return $err;
114
    }
115
116
    /**
117
     * Returns the provided exception as a normalize associative array.
118
     *
119
     * @param  \Exception $e
120
     * @return array
121
     */
122
    public static function toArray(\Exception $e)
123
    {
124
        $array = array(
125
            'message' => $e->getMessage(),
126
            'code'    => $e->getCode(),
127
            'type'    => get_class($e),
128
            'file'    => $e->getFile(),
129
            'line'    => $e->getLine(),
130
            'trace'   => $e->getTraceAsString(),
131
        );
132
133
        if (method_exists($e, 'getPrevious')) {
134
            $p = $e->getPrevious();
135
            if (method_exists($p, 'getTraceAsString')) {
136
                $array['prev'] = $p->getTraceAsString();
137
            }
138
        }
139
140
        return $array;
141
    }
142
143
}
144