-
Notifications
You must be signed in to change notification settings - Fork 2
/
Exception.php
58 lines (48 loc) · 1.57 KB
/
Exception.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
declare(strict_types=1);
namespace ManaPHP;
use ManaPHP\Helper\SuppressWarnings;
use Stringable;
use function is_array;
use function is_string;
class Exception extends \Exception
{
protected array $json = [];
public function __construct(string|Stringable|array $message = '', int $code = 0, \Exception $previous = null)
{
if (is_array($message)) {
$replaces = [];
preg_match_all('#{(\w+)}#', $message[0], $matches);
foreach ($matches[1] as $key) {
if (($val = $message[$key] ?? null) !== null) {
if (is_string($val)) {
SuppressWarnings::noop();
} elseif ($val instanceof Stringable) {
$val = (string)$val;
} else {
$val = json_stringify($val);
}
$replaces['{' . $key . '}'] = $val;
}
}
$message = strtr($message[0], $replaces);
} elseif ($message instanceof Stringable) {
$message = (string)$message;
}
parent::__construct($message, $code, $previous);
}
public function getStatusCode(): int
{
return 500;
}
public function getJson(): array
{
if ($this->json) {
return $this->json;
} else {
$code = $this->getStatusCode();
$message = $code === 500 ? 'Server Internal Error' : $this->getMessage();
return ['code' => $code === 200 ? -1 : $code, 'msg' => $message];
}
}
}