1 | <?php |
||
29 | class CaptureError implements CaptureErrorInterface |
||
30 | { |
||
31 | /** |
||
32 | * The callable to be processed |
||
33 | * |
||
34 | * @var callable |
||
35 | */ |
||
36 | protected $callable; |
||
37 | |||
38 | /** |
||
39 | * Last error message |
||
40 | * |
||
41 | * @var string |
||
42 | */ |
||
43 | protected $last_error_message = ''; |
||
44 | |||
45 | /** |
||
46 | * Last error code |
||
47 | * |
||
48 | * @var int |
||
49 | */ |
||
50 | protected $last_error_code = 0; |
||
51 | |||
52 | /** |
||
53 | * PHP error reporting level |
||
54 | * |
||
55 | * @var int |
||
56 | */ |
||
57 | protected $error_level; |
||
58 | |||
59 | /** |
||
60 | * A new instance |
||
61 | * |
||
62 | * @param callable $callable The code to capture error from |
||
63 | * @param int $error_level error reporting level |
||
64 | */ |
||
65 | public function __construct(callable $callable, $error_level = E_ALL) |
||
66 | { |
||
67 | $this->callable = $callable; |
||
68 | $this->setErrorReporting($error_level); |
||
69 | } |
||
70 | |||
71 | /** |
||
72 | * Set the Error Reporting level |
||
73 | * |
||
74 | * @param int $error_level error reporting level |
||
75 | * |
||
76 | * @throws InvalidArgumentException If the reporting level is not a positive int |
||
77 | */ |
||
78 | protected function setErrorReporting($error_level) |
||
79 | { |
||
80 | if (!filter_var($error_level, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]])) { |
||
81 | throw new InvalidArgumentException('Expected data must to be positive integer'); |
||
82 | } |
||
83 | |||
84 | $this->error_level = $error_level; |
||
85 | } |
||
86 | |||
87 | /** |
||
88 | * Get the current Error Reporting Level |
||
89 | * |
||
90 | * @return int |
||
91 | */ |
||
92 | public function getErrorReporting() |
||
96 | |||
97 | /** |
||
98 | * @inheritdoc |
||
99 | */ |
||
100 | public function __invoke() |
||
101 | { |
||
102 | $errorHandler = function ($code, $message) { |
||
103 | $this->last_error_code = $code; |
||
104 | $this->last_error_message = $message; |
||
105 | }; |
||
106 | |||
107 | $this->last_error_code = 0; |
||
108 | $this->last_error_message = ''; |
||
109 | set_error_handler($errorHandler, $this->error_level); |
||
110 | $result = call_user_func_array($this->callable, func_get_args()); |
||
111 | restore_error_handler(); |
||
112 | |||
113 | return $result; |
||
114 | } |
||
115 | |||
116 | /** |
||
117 | * @inheritdoc |
||
118 | */ |
||
119 | public function getLastErrorCode() |
||
123 | |||
124 | /** |
||
125 | * @inheritdoc |
||
126 | */ |
||
127 | public function getLastErrorMessage() |
||
131 | } |
||
132 |