Test Failed
Push — dev ( e79643...3785bc )
by 世昌
04:25
created

ExceptionCatcher::restore()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
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
     * @return void
49
     */
50
    public static function restore() {
51
        restore_exception_handler();
52
    }
53
54
    /**
55
     * 异常托管
56
     *
57
     * @param Throwable $exception
58
     * @return void
59
     * @throws Exception
60
     */
61
    public function uncaughtException($exception)
62
    {
63
        $this->applicationContext->debug()->addIgnorePath(__FILE__);
64
        $this->applicationContext->debug()->uncaughtException($exception);
65
        $this->dumpThrowable($exception);
66
    }
67
68
    /**
69
     * @param Throwable $throwable
70
     */
71
    public function dumpThrowable($throwable)
72
    {
73
        $dumpPath = $this->applicationContext->conf('save-dump-path');
74
        if ($dumpPath !== null) {
75
            $this->context['application'] = $this->applicationContext;
76
            $dumper = [
77
                'time' => time(),
78
                'throwable' => $throwable,
79
                'context' => $this->context,
80
                'backtrace' => $throwable->getTrace(),
81
            ];
82
            $exceptionHash = md5($throwable->getFile() . $throwable->getLine() . $throwable->getCode());
83
            $path = $dumpPath . '/' . microtime(true) . '.' . substr($exceptionHash, 0, 8) . '.json';
84
            FileSystem::make($dumpPath);
85
            FileSystem::put($path, json_encode(
86
                new DebugObject($dumper),
87
                JSON_PRETTY_PRINT
88
                | JSON_UNESCAPED_UNICODE
89
            ));
90
        }
91
    }
92
}