Completed
Push — master ( 5a5aff...6d6efd )
by Joram van den
04:02
created

Ajde_Exception_Handler   C

Complexity

Total Complexity 77

Size/Duplication

Total Lines 318
Duplicated Lines 11.32 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 12
Bugs 4 Features 0
Metric Value
wmc 77
c 12
b 4
f 0
lcom 1
cbo 11
dl 36
loc 318
rs 5.3019

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __bootstrap() 0 12 1
A errorHandler() 0 15 2
B handler() 0 22 6
D trace() 8 124 28
A getTypeDescription() 0 12 4
B getExceptionChannelMap() 14 14 5
B getExceptionLevelMap() 14 14 5
D getErrorType() 0 37 17
C embedScript() 0 50 9

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Ajde_Exception_Handler 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 Ajde_Exception_Handler, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
class Ajde_Exception_Handler extends Ajde_Object_Static
4
{
5
    public static function __bootstrap()
6
    {
7
        // making xdebug.overload_var_dump = 1 work
8
        //if (Config::get('debug')) {
9
        ini_set('html_errors', 1);
10
        //}
11
        // TODO: why is this defined here? also in index.php!
12
        set_error_handler(['Ajde_Exception_Handler', 'errorHandler']);
13
        set_exception_handler(['Ajde_Exception_Handler', 'handler']);
14
15
        return true;
16
    }
17
18
    public static function errorHandler($errno, $errstr, $errfile, $errline)
19
    {
20
        if (error_reporting() > 0) {
21
            $message = sprintf("PHP error: %s in %s on line %s", $errstr, $errfile, $errline);
22
            error_log($message);
23
            dump($message);
24
25
            // TODO: only possible in PHP >= 5.3 ?
26
//			try
27
//			{
28
            throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
29
//			} catch(Exception $exception) {
30
//			}
31
        }
32
    }
33
34
    public static function handler(Exception $exception)
0 ignored issues
show
Unused Code introduced by
The parameter $exception is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
35
    {
36
        try {
37
            if (Config::getInstance()->debug === true) {
0 ignored issues
show
Documentation introduced by
The property debug does not exist on object<Config>. 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...
38
                if (!((get_class($exception) == 'Ajde_Exception' || is_subclass_of($exception,
39
                            'Ajde_Exception')) && !$exception->traceOnOutput())
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method traceOnOutput() does only exist in the following sub-classes of Exception: Ajde_Component_Exception, Ajde_Controller_Exception, Ajde_Core_Autoloader_Exception, Ajde_Core_Exception_Deprecated, Ajde_Core_Exception_Routing, Ajde_Core_Exception_Security, Ajde_Db_Exception, Ajde_Db_IntegrityException, Ajde_Exception. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
40
                ) {
41
                    Ajde_Exception_Log::logException($exception);
42
                    echo self::trace($exception);
43
                } else {
44
                    Ajde_Exception_Log::logException($exception);
45
                    Ajde_Http_Response::redirectServerError();
46
                }
47
            } else {
48
                Ajde_Exception_Log::logException($exception);
49
                Ajde_Http_Response::redirectServerError();
50
            }
51
        } catch (Exception $exception) {
52
            error_log(self::trace($exception, self::EXCEPTION_TRACE_LOG));
53
            die("An uncatched exception occured within the error handler, see the server error_log for details");
54
        }
55
    }
56
57
    const EXCEPTION_TRACE_HTML = 1;
58
    const EXCEPTION_TRACE_ONLY = 3;
59
    const EXCEPTION_TRACE_LOG = 2;
60
61
    public static function trace(Exception $exception, $output = self::EXCEPTION_TRACE_HTML)
62
    {
63
        $simpleJsonTrace = false;
64
        if ($simpleJsonTrace && Ajde::app()->hasDocument() && Ajde::app()->getDocument()->getFormat() == 'json') {
0 ignored issues
show
Documentation Bug introduced by
The method hasDocument does not exist on object<Ajde_Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
Documentation Bug introduced by
The method getFormat does not exist on object<Ajde_Document>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
65
            $output = self::EXCEPTION_TRACE_LOG;
66
        }
67
68
        $type = self::getTypeDescription($exception);
69
70
        switch ($output) {
71
            case self::EXCEPTION_TRACE_HTML:
72
                if (ob_get_level()) {
73
                    ob_clean();
74
                }
75
76
                $traceMessage = '<ol reversed="reversed">';
77
                self::$firstApplicationFileExpanded = false;
78
                foreach ($exception->getTrace() as $item) {
79
                    $arguments = null;
80
                    if (!empty($item['args'])) {
81
                        ob_start();
82
                        var_dump($item['args']);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($item['args']); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
83
                        $dump = ob_get_clean();
84
                        $arguments = sprintf(' with arguments: %s', $dump);
85
                    }
86
                    $traceMessage .= sprintf("<li><code><em>%s</em>%s<strong>%s</strong></code><br/>in %s<br/>&nbsp;\n",
87
                        !empty($item['class']) ? $item['class'] : '&lt;unknown class&gt;',
88
                        !empty($item['type']) ? $item['type'] : '::',
89
                        !empty($item['function']) ? $item['function'] : '&lt;unknown function&gt;',
90
                        self::embedScript(
91
                            issetor($item['file'], null),
92
                            issetor($item['line'], null),
93
                            $arguments,
94
                            false
95
                        ));
96
                    $traceMessage .= '</li>';
97
                }
98
                $traceMessage .= '</ol>';
99
100
                $exceptionDocumentation = '';
101
                if ($exception instanceof Ajde_Exception && $exception->getCode()) {
102
                    $exceptionDocumentation = sprintf("<div style='margin-top: 4px;'><img src='" . Config::get('site_root') . MEDIA_URI . "_core/globe_16.png' style='vertical-align: bottom;' title='Primary key' width='16' height='16' /> <a href='%s'>Documentation on error %s</a>&nbsp;</div>",
103
                        Ajde_Core_Documentation::getUrl($exception->getCode()),
104
                        $exception->getCode()
105
                    );
106
                }
107
108
                $exceptionMessage = sprintf("<summary style='background-image: url(\"" . Config::get('site_root') . MEDIA_URI . "_core/warning_48.png\");'><h3 style='margin:0;'>%s:</h3><h2 style='margin:0;'>%s</h2> Exception thrown in %s%s</summary><h3>Trace:</h3>\n",
109
                    $type,
110
                    $exception->getMessage(),
111
                    self::embedScript(
112
                        $exception->getFile(),
113
                        $exception->getLine(),
114
                        $arguments,
0 ignored issues
show
Bug introduced by
The variable $arguments does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
115
                        false //!self::$firstApplicationFileExpanded
116
                    ),
117
                    $exceptionDocumentation
118
                );
119
120
                $exceptionDump = '';
121
                if (class_exists(Ajde_Dump::class)) {
122
                    if ($dumps = Ajde_Dump::getAll()) {
123
                        $exceptionDump .= '<h2>Dumps</h2>';
124
                        foreach ($dumps as $source => $dump) {
125
                            ob_start();
126
                            echo $source;
127
                            if (class_exists(Kint::class)) {
128
                                Kint::dump($dump[0]);
129
                            } else {
130
                                echo '<pre>';
131
                                var_dump($dump[0]);
132
                                echo '</pre>';
133
                            }
134
                            $exceptionDump .= ob_get_clean() . '<h2>Error message</h2>';
135
                        }
136
                    }
137
                }
138
139
                $style = false;
140
                if (file_exists(CORE_DIR . MODULE_DIR . '_core/res/css/debugger/handler.css')) {
141
                    $style = file_get_contents(CORE_DIR . MODULE_DIR . '_core/res/css/debugger/handler.css');
142
                }
143
                if ($style === false) {
144
                    // For shutdown() call
145
                    $style = 'body {font: 13px sans-serif;} a {color: #005D9A;} a:hover {color: #9A0092;} h2 {color: #005D9A;} span > a {color: #9A0092;}';
146
                }
147
                $style = '<style>' . $style . '</style>';
148
                $script = '<script>document.getElementsByTagName("base")[0].href="";</script>';
149
150
                if (Ajde::app()->getRequest()->isAjax()) {
151
                    $collapsed = $exceptionDump . $exceptionMessage . $traceMessage;
152
                    $header = '';
153
                } else {
154
                    $collapsed = '<div id="details">' . $exceptionDump . $exceptionMessage . $traceMessage . '</div>';
155
                    $header = '<header><h1><img src="' . Config::get('site_root') . MEDIA_URI . 'ajde-small.png">Something went wrong</h1><a href="javascript:history.go(-1);">Go back</a> <a href="#details">Show details</a></header>';
156
                }
157
158
                $message = $style . $script . $header . $collapsed;
159
                break;
160
            case self::EXCEPTION_TRACE_ONLY:
161
                $message = '';
162 View Code Duplication
                foreach (array_reverse($exception->getTrace()) as $i => $line) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
163
                    $message .= $i . '. ' . (isset($line['file']) ? $line['file'] : 'unknown file') . ' on line ' . (isset($line['line']) ? $line['line'] : 'unknown line');
164
                    $message .= PHP_EOL;
165
                }
166
                break;
167
            case self::EXCEPTION_TRACE_LOG:
168
                $message = 'UNCAUGHT EXCEPTION' . PHP_EOL;
169
                $message .= "\tRequest " . $_SERVER["REQUEST_URI"] . " triggered:" . PHP_EOL;
170
                $message .= sprintf("\t%s: %s in %s on line %s",
171
                    $type,
172
                    $exception->getMessage(),
173
                    $exception->getFile(),
174
                    $exception->getLine()
175
                );
176 View Code Duplication
                foreach (array_reverse($exception->getTrace()) as $i => $line) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
                    $message .= PHP_EOL;
178
                    $message .= "\t" . $i . '. ' . (isset($line['file']) ? $line['file'] : 'unknown file') . ' on line ' . (isset($line['line']) ? $line['line'] : 'unknown line');
179
                }
180
                break;
181
        }
182
183
        return $message;
0 ignored issues
show
Bug introduced by
The variable $message does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
184
    }
185
186
    public static function getTypeDescription(Exception $exception)
187
    {
188
        if ($exception instanceof ErrorException) {
189
            $type = "PHP Error " . self::getErrorType($exception->getSeverity());
190
        } elseif ($exception instanceof Ajde_Exception) {
191
            $type = "Application exception" . ($exception->getCode() ? ' ' . $exception->getCode() : '');
192
        } else {
193
            $type = "PHP exception " . $exception->getCode();
194
        }
195
196
        return $type;
197
    }
198
199 View Code Duplication
    public static function getExceptionChannelMap(Exception $exception)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
200
    {
201
        if ($exception instanceof ErrorException) {
202
            return Ajde_Log::CHANNEL_ERROR;
203
        } elseif ($exception instanceof Ajde_Core_Exception_Routing) {
204
            return Ajde_Log::CHANNEL_ROUTING;
205
        } elseif ($exception instanceof Ajde_Core_Exception_Security) {
206
            return Ajde_Log::CHANNEL_SECURITY;
207
        } elseif ($exception instanceof Ajde_Exception) {
208
            return Ajde_Log::CHANNEL_APPLICATION;
209
        } else {
210
            return Ajde_Log::CHANNEL_EXCEPTION;
211
        }
212
    }
213
214 View Code Duplication
    public static function getExceptionLevelMap(Exception $exception)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
215
    {
216
        if ($exception instanceof ErrorException) {
217
            return Ajde_Log::LEVEL_ERROR;
218
        } elseif ($exception instanceof Ajde_Core_Exception_Routing) {
219
            return Ajde_Log::LEVEL_WARNING;
220
        } elseif ($exception instanceof Ajde_Core_Exception_Security) {
221
            return Ajde_Log::LEVEL_WARNING;
222
        } elseif ($exception instanceof Ajde_Exception) {
223
            return Ajde_Log::LEVEL_ERROR;
224
        } else {
225
            return Ajde_Log::LEVEL_ERROR;
226
        }
227
    }
228
229
    public static function getErrorType($type)
230
    {
231
        switch ($type) {
232
            case 1:
233
                return "E_ERROR";
234
            case 2:
235
                return "E_WARNING";
236
            case 4:
237
                return "E_PARSE";
238
            case 8:
239
                return "E_NOTICE";
240
            case 16:
241
                return "E_CORE_ERROR";
242
            case 32:
243
                return "E_CORE_WARNING";
244
            case 64:
245
                return "E_COMPILE_ERROR";
246
            case 128:
247
                return "E_COMPILE_WARNING";
248
            case 256:
249
                return "E_USER_ERROR";
250
            case 512:
251
                return "E_USER_WARNING";
252
            case 1024:
253
                return "E_USER_NOTICE";
254
            case 2048:
255
                return "E_STRICT";
256
            case 4096:
257
                return "E_RECOVERABLE_ERROR";
258
            case 8192:
259
                return "E_DEPRECATED";
260
            case 16384:
261
                return "E_USER_DEPRECATED";
262
            case 30719:
263
                return "E_ALL";
264
        }
265
    }
266
267
    static $firstApplicationFileExpanded = false;
268
269
    protected static function embedScript($filename = null, $line = null, $arguments = null, $expand = false)
270
    {
271
        $lineOffset = 5;
272
        $file = '';
273
274
        // in case of eval, filename looks like File.php(30) : eval()'d code
275
        if (substr_count($filename, '(')) {
276
            list($filename) = explode('(', $filename);
277
        }
278
279
        if (isset($filename) && isset($line)) {
280
            $lines = file($filename);
281
            for ($i = max(0, $line - $lineOffset - 1); $i < min($line + $lineOffset, count($lines)); $i++) {
282
                $lineNumber = str_repeat(" ", 4 - strlen($i + 1)) . ($i + 1);
283
                if ($i == $line - 1) {
284
                    $file .= "{{{}}}" . $lineNumber . ' ' . ($lines[$i]) . "{{{/}}}";
285
                } else {
286
                    $file .= $lineNumber . ' ' . ($lines[$i]);
287
                }
288
            }
289
        }
290
291
        if (substr_count($filename, str_replace('/', DIRECTORY_SEPARATOR, APP_DIR))) {
292
            $filename = '<span style="color: red;">' . $filename . '</span>';
293
            if (self::$firstApplicationFileExpanded === false) {
294
                $expand = true;
295
            }
296
            self::$firstApplicationFileExpanded = true;
297
        }
298
        $file = highlight_string("<?php" . $file, true);
299
        $file = str_replace('&lt;?php', '', $file);
300
        $file = str_replace('<code>',
301
            "<code style='display:block;border:1px solid silver;margin:5px 0 5px 0;background-color:#f1f1f1;'>", $file);
302
        $file = str_replace('{{{}}}', "<div style='background-color: #ffff9e;'>", $file);
303
        $file = str_replace('{{{/}}}', "</div>", $file);
304
305
        $id = md5(microtime() . $filename . $line);
306
307
        return sprintf(
308
            "<a
309
					onclick='document.getElementById(\"$id\").style.display = document.getElementById(\"$id\").style.display == \"block\" ? \"none\" : \"block\";'
310
					href='javascript:void(0);'
311
				><i>%s</i> on line <b>%s</b></a>&nbsp;<div id='$id' style='display:%s;'>%s%s</div>",
312
            $filename,
313
            $line,
314
            $expand ? "block" : "none",
315
            $file,
316
            $arguments
317
        );
318
    }
319
320
}
321