Passed
Push — master ( acba12...b2f89b )
by 世昌
04:15
created

ExceptionCatcher::uncaughtException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php
2
3
namespace suda\application\debug;
4
5
use Throwable;
6
use Exception;
7
use suda\framework\Context;
8
use suda\framework\debug\DebugObject;
9
use suda\application\ApplicationContext;
10
use suda\framework\filesystem\FileSystem;
11
12
class ExceptionCatcher
13
{
14
    /**
15
     * 应用
16
     *
17
     * @var ApplicationContext
18
     */
19
    protected $applicationContext;
20
21
    /**
22
     * @var array
23
     */
24
    protected $context;
25
26
    /**
27
     * ExceptionCatcher constructor.
28
     * @param ApplicationContext $application
29
     * @param array $context
30
     */
31
    public function __construct(ApplicationContext $application, array $context)
32
    {
33
        $this->applicationContext = $application;
34
        $this->context = $context;
35
    }
36
37
    /**
38
     * 注册错误处理函数
39
     * @return self
40
     */
41
    public function register()
42
    {
43
        set_exception_handler([$this, 'uncaughtException']);
44
        return $this;
45
    }
46
47
    /**
48
     * 异常托管
49
     *
50
     * @param Throwable $exception
51
     * @return void
52
     * @throws Exception
53
     */
54
    public function uncaughtException($exception)
55
    {
56
        $this->applicationContext->debug()->addIgnorePath(__FILE__);
57
        $this->applicationContext->debug()->uncaughtException($exception);
58
        $this->dumpThrowable($exception);
59
    }
60
61
    /**
62
     * @param Throwable $throwable
63
     */
64
    public function dumpThrowable($throwable)
65
    {
66
        $dumpPath = $this->applicationContext->conf('save-dump-path');
67
        if ($dumpPath !== null) {
68
            $this->context['application'] = $this->applicationContext;
69
            $dumper = [
70
                'time' => time(),
71
                'throwable' => $throwable,
72
                'context' => $this->context,
73
                'backtrace' => $throwable->getTrace(),
74
            ];
75
            $exceptionHash = md5($throwable->getFile() . $throwable->getLine() . $throwable->getCode());
76
            $path = $dumpPath . '/' . microtime(true) . '.' . substr($exceptionHash, 0, 8) . '.json';
77
            FileSystem::make($dumpPath);
78
            FileSystem::put($path, json_encode(
79
                new DebugObject($dumper),
80
                JSON_PRETTY_PRINT
81
                | JSON_UNESCAPED_UNICODE
82
            ));
83
        }
84
    }
85
}