1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace BEAR\Resource\SemanticLog\Profile\Verbose; |
6
|
|
|
|
7
|
|
|
use BEAR\Resource\SemanticLog\Profile\PhpProfile; |
8
|
|
|
use BEAR\Resource\SemanticLog\Profile\Profile; |
9
|
|
|
use JsonSerializable; |
10
|
|
|
use Koriym\SemanticLogger\AbstractContext; |
11
|
|
|
use Override; |
12
|
|
|
use Throwable; |
13
|
|
|
|
14
|
|
|
use function crc32; |
15
|
|
|
use function dechex; |
16
|
|
|
|
17
|
|
|
final class ErrorContext extends AbstractContext implements JsonSerializable |
18
|
|
|
{ |
19
|
|
|
/** @psalm-suppress InvalidClassConstantType */ |
20
|
|
|
public const TYPE = 'bear_resource_error'; |
21
|
|
|
|
22
|
|
|
/** @psalm-suppress InvalidClassConstantType */ |
23
|
|
|
public const SCHEMA_URL = 'https://bearsunday.github.io/BEAR.Resource/schemas/error-context.json'; |
24
|
|
|
|
25
|
|
|
public readonly string $exceptionId; |
26
|
|
|
public readonly string $exceptionAsString; |
27
|
|
|
public readonly Profile $profile; |
28
|
|
|
|
29
|
|
|
public function __construct( |
30
|
|
|
Throwable $exception, |
31
|
|
|
string $exceptionId = '', |
32
|
|
|
?OpenContext $openContext = null, |
33
|
|
|
) { |
34
|
|
|
$this->exceptionAsString = (string) $exception; |
|
|
|
|
35
|
|
|
$this->exceptionId = $exceptionId !== '' ? $exceptionId : $this->createExceptionId(); |
|
|
|
|
36
|
|
|
|
37
|
|
|
if ($openContext === null) { |
38
|
|
|
// Create empty profile if no open context provided |
39
|
|
|
$this->profile = new Profile(); |
|
|
|
|
40
|
|
|
|
41
|
|
|
return; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
// Stop profiling through the openContext's profile objects |
45
|
|
|
$xhprofResult = $openContext->profile->xhprof?->stop($openContext->uri); |
46
|
|
|
$xdebugTrace = $openContext->profile->xdebug?->stop(); |
47
|
|
|
$phpProfile = PhpProfile::capture(); |
48
|
|
|
|
49
|
|
|
$this->profile = new Profile( |
50
|
|
|
xhprof: $xhprofResult, |
51
|
|
|
xdebug: $xdebugTrace, |
52
|
|
|
php: $phpProfile, |
53
|
|
|
); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
public static function create( |
57
|
|
|
Throwable $exception, |
58
|
|
|
string $exceptionId = '', |
59
|
|
|
?OpenContext $openContext = null, |
60
|
|
|
): self { |
61
|
|
|
return new self($exception, $exceptionId, $openContext); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
private function createExceptionId(): string |
65
|
|
|
{ |
66
|
|
|
$crc = crc32($this->exceptionAsString); |
67
|
|
|
$crcHex = dechex($crc & 0xFFFFFFFF); // Ensure positive hex value |
68
|
|
|
|
69
|
|
|
return 'e-bear-resource-' . $crcHex; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** @return array<string, mixed> */ |
73
|
|
|
#[Override] |
74
|
|
|
public function jsonSerialize(): array |
75
|
|
|
{ |
76
|
|
|
return [ |
77
|
|
|
'exceptionId' => $this->exceptionId, |
78
|
|
|
'exceptionAsString' => $this->exceptionAsString, |
79
|
|
|
'profile' => $this->profile, |
80
|
|
|
]; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|