Completed
Push — master ( 6f7c35...34cdf9 )
by Mathieu
02:07
created

Error::handleError()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 5
dl 0
loc 4
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
namespace Suricate;
3
4
use ErrorException;
5
6
class Error extends Service
7
{
8
    protected $parametersList   = array(
9
        'report',
10
        'dumpContext',
11
        'httpHandler'
12
        );
13
14
    public static function handleException($e, $context = null)
15
    {
16
        if ($e instanceof Exception\HttpException) {
17
            $httpHandler = Suricate::Error()->httpHandler;
18
            if (is_object($httpHandler) && ($httpHandler instanceof \Closure)) {
19
                $httpHandler($e);
20
                return;
21
            } elseif ($httpHandler != '') {
22
                $httpHandler = explode('::', $httpHandler);
23
                if (count($httpHandler) > 1) {
24
                    call_user_func($httpHandler, $e);
25
                } else {
26
                    call_user_func(head($httpHandler), $e);
27
                }
28
29
                return;
30
            }
31
            
32
            Suricate::Error()->displayGenericHttpExceptionPage($e);
33
        }
34
35
        while (ob_get_level() > 1) {
36
            ob_end_clean();
37
        }
38
        
39
        $json = [];
40
        $error = $e;
41
        do {
42
            $json[] = [
43
                'type' => get_class($error),
44
                'code' => $error->getCode(),
45
                'message' => $error->getMessage(),
46
                'file' => $error->getFile(),
47
                'line' => $error->getLine(),
48
                'trace' => explode("\n", $error->getTraceAsString()),
49
            ];
50
        } while ($error = $error->getPrevious());
51
        Suricate::Logger()->error(json_encode($json));
52
53
        Suricate::Error()->displayExceptionPage($e, $context);
54
    }
55
56
    public static function handleError($code, $message, $file, $line, $context)
57
    {
58
        static::handleException(new ErrorException($message, $code, 0, $file, $line), $context);
59
    }
60
61
    public static function handleShutdownError()
62
    {
63
        if ($error = error_get_last()) {
64
            static::handleException(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));
65
        }
66
    }
67
68
    private function displayExceptionPage($e, $context = null)
69
    {
70
        if ($this->report || $this->report === null) {
0 ignored issues
show
Documentation introduced by
The property report does not exist on object<Suricate\Error>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
71
            echo '<html>'."\n";
72
            echo '  <head>'."\n";
73
            echo '      <title>Oops, Uncaught Exception</title>'."\n";
74
            echo '      <style>'."\n";
75
            echo '          body{font-family: "Open Sans",arial,sans-serif; background: #FFF; color:#333; margin:2em}'."\n";
76
            echo '          code{background:#E0941B;border-radius:4px;padding:2px 6px}'."\n";
77
            echo '      </style>'."\n";
78
            echo '  </head>'."\n";
79
            echo '  <body>'."\n";
80
            echo '      <h1>Oops, uncaught exception !</h1>'."\n";
81
            echo '      <h2>This is embarrassing, but server made a booboo</h2>'."\n";
82
            echo '      <p><code>' . $e->getMessage() . '</code></p>'."\n";
83
            echo '      <h3>From:</h3>'."\n";
84
            echo '      <p><code>' . $e->getFile() . ' on line ' . $e->getLine() . '</code></p>'."\n";
85
            echo '      <h3>Call stack</h3>'."\n";
86
            echo '      <pre>' . $e->getTraceAsString() . '</pre>'."\n";
87
            if ($this->dumpContext) {
0 ignored issues
show
Documentation introduced by
The property dumpContext does not exist on object<Suricate\Error>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
88
                echo '<h3>Context:</h3>';
89
                _p($context);
90
            }
91
            echo '  </body>'."\n";
92
            echo '</html>';
93
        } else {
94
            if ($e->getCode() <= 1) {
95
                $err = new Exception\HttpException('500');
96
                $this->displayGenericHttpExceptionPage($err);
97
            }
98
        }
99
        exit(1);
0 ignored issues
show
Coding Style Compatibility introduced by
The method displayExceptionPage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
100
    }
101
102
    private function displayGenericHttpExceptionPage($e)
103
    {
104
        $response = Suricate::Request();
105
106
        if (is_readable(app_path() . '/views/Errors/' . $e->getStatusCode() . '.php')) {
107
            ob_start();
108
            include app_path() . '/views/Errors/' . $e->getStatusCode() . '.php';
109
            $body = ob_get_clean();
110
        } else {
111
            $innerHtml = '<h1>' . $e->getStatusCode()  .'</h1>';
112
            
113
            $page = new Page();
114
            $body = $page
115
                ->setTitle($e->getStatusCode())
116
                ->render($innerHtml);
117
        }
118
        
119
        $response
120
            ->setBody($body)
121
            ->setHttpCode($e->getStatusCode());
122
        foreach ($e->getHeaders() as $header => $value) {
123
            $response->addHeader($header, $value);
124
        }
125
126
        $response->write();
127
        die();
0 ignored issues
show
Coding Style Compatibility introduced by
The method displayGenericHttpExceptionPage() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
128
    }
129
}
130