Repository navigation
Expand file tree
/
Copy pathExceptionNormalizer.php
More file actions
105 lines (95 loc) · 3.12 KB
/
Copy pathExceptionNormalizer.php
File metadata and controls
105 lines (95 loc) · 3.12 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://doc.hyperf.io
* @contact [email protected]
* @license https://github.com/hyperf-cloud/hyperf/blob/master/LICENSE
*/
namespace Hyperf\Utils\Serializer;
use Hyperf\Di\ReflectionManager;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
class ExceptionNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface
{
/**
* {@inheritdoc}
*/
public function denormalize($data, $class, $format = null, array $context = [])
{
if (is_string($data)) {
$ex = unserialize($data);
if ($ex instanceof \Exception) {
return $ex;
}
// Retry handle it if the exception not instanceof \Exception.
$data = $ex;
}
if (is_array($data) && isset($data['message'], $data['code'])) {
try {
$exception = new $class($data['message'], $data['code']);
foreach (['file', 'line'] as $attribute) {
if (isset($data[$attribute])) {
$property = ReflectionManager::reflectProperty($class, $attribute);
$property->setAccessible(true);
$property->setValue($exception, $data[$attribute]);
}
}
return $exception;
} catch (\ReflectionException $e) {
return new \RuntimeException(sprintf(
'Bad data %s: %s',
$data['class'],
$data['message']
), $data['code']);
} catch (\TypeError $e) {
return new \RuntimeException(sprintf(
'Uncaught data %s: %s',
$data['class'],
$data['message']
), $data['code']);
}
}
return new \RuntimeException('Bad data data: ' . json_encode($data));
}
/**
* {@inheritdoc}
*/
public function supportsDenormalization($data, $type, $format = null)
{
return class_exists($type) && is_a($type, \Exception::class, true);
}
/**
* {@inheritdoc}
*/
public function normalize($object, $format = null, array $context = [])
{
if ($object instanceof \Serializable) {
return serialize($object);
}
/* @var \Exception $object */
return [
'message' => $object->getMessage(),
'code' => $object->getCode(),
'file' => $object->getFile(),
'line' => $object->getLine(),
];
}
/**
* {@inheritdoc}
*/
public function supportsNormalization($data, $format = null)
{
return $data instanceof \Exception;
}
/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool
{
return \get_class($this) === __CLASS__;
}
}