Passed
Push — master ( 35ff5f...63edb8 )
by Ion
03:15
created

LogService::getExceptionTraceAsString()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 20
c 1
b 0
f 0
nc 18
nop 1
dl 0
loc 34
rs 8.9777
1
<?php
2
3
namespace App\Services;
4
5
use App\Models\User;
6
use Exception;
7
use Illuminate\Support\Facades\Auth;
8
9
/**
10
 * Class LogService
11
 *
12
 * @package App\Services
13
 */
14
class LogService
15
{
16
    /**
17
     * Get full trace of an exception.
18
     *
19
     * @param Exception $exception
20
     *
21
     * @return string
22
     */
23
    public static function getExceptionTraceAsString(Exception $exception)
24
    {
25
        $errorString = "#00 User: ";
26
27
        /** @var User|null $user */
28
        $user = Auth::user();
29
30
        if ($user) {
0 ignored issues
show
introduced by
$user is of type App\Models\User, thus it always evaluated to true.
Loading history...
31
            $errorString .= $user->id . ' ' . $user->name;
32
        }
33
34
        $errorString .= "\n";
35
        $count = 0;
36
37
        foreach ($exception->getTrace() as $frame) {
38
            $args = "";
39
40
            if (isset($frame['args'])) {
41
                $args = self::getFrameArgs($frame['args']);
42
            }
43
44
            $currentFile = isset($frame['file']) ? $frame['file'] : '[internal function]';
45
            $currentLine = isset($frame['line']) ? $frame['line'] : '';
46
47
            $errorString .= sprintf("#%s %s(%s): %s(%s)\n",
48
                $count,
49
                $currentFile,
50
                $currentLine,
51
                $frame['function'],
52
                $args);
53
            $count++;
54
        }
55
56
        return $errorString . "\n";
57
    }
58
59
    /**
60
     * Get exception args
61
     *
62
     * @param $frameArgs
63
     *
64
     * @return string
65
     */
66
    private static function getFrameArgs($frameArgs)
67
    {
68
        $args = array();
69
70
        foreach ($frameArgs as $arg) {
71
            if (is_string($arg)) {
72
                $args[] = "'" . $arg . "'";
73
            } elseif (is_array($arg)) {
74
                $args[] = "Array";
75
            } elseif (is_null($arg)) {
76
                $args[] = 'NULL';
77
            } elseif (is_bool($arg)) {
78
                $args[] = ($arg) ? "true" : "false";
79
            } elseif (is_object($arg)) {
80
                $args[] = get_class($arg);
81
            } elseif (is_resource($arg)) {
82
                $args[] = get_resource_type($arg);
83
            } else {
84
                $args[] = $arg;
85
            }
86
        }
87
88
        return join(", ", $args);
89
    }
90
}
91