Passed
Pull Request — 1.x (#334)
by Akihito
02:32
created

ErrorContext::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
nc 2
nop 3
dl 0
loc 10
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource\SemanticLog\Profile\Compact;
6
7
use Koriym\SemanticLogger\AbstractContext;
8
use Throwable;
9
10
use function crc32;
11
use function dechex;
12
13
final class ErrorContext extends AbstractContext
14
{
15
    /** @psalm-suppress InvalidClassConstantType */
16
    public const TYPE = 'bear_resource_error';
17
18
    /** @psalm-suppress InvalidClassConstantType */
19
    public const SCHEMA_URL = 'https://bearsunday.github.io/BEAR.Resource/schemas/error-context.json';
20
21
    public readonly string $exceptionId;
22
    public readonly string $exceptionAsString;
23
24
    public function __construct(
25
        Throwable $exception,
26
        string $exceptionId = '',
27
        ?OpenContext $openContext = null,
28
    ) {
29
        $this->exceptionAsString = (string) $exception;
0 ignored issues
show
Bug introduced by
The property exceptionAsString is declared read-only in BEAR\Resource\SemanticLo...le\Compact\ErrorContext.
Loading history...
30
        $this->exceptionId = $exceptionId !== '' ? $exceptionId : $this->createExceptionId();
0 ignored issues
show
Bug introduced by
The property exceptionId is declared read-only in BEAR\Resource\SemanticLo...le\Compact\ErrorContext.
Loading history...
31
32
        // OpenContext is intentionally unused in Compact profile (no profiling)
33
        unset($openContext);
34
    }
35
36
    public static function create(
37
        Throwable $exception,
38
        string $exceptionId = '',
39
        ?OpenContext $openContext = null,
40
    ): self {
41
        return new self($exception, $exceptionId, $openContext);
42
    }
43
44
    private function createExceptionId(): string
45
    {
46
        $crc = crc32($this->exceptionAsString);
47
        $crcHex = dechex($crc & 0xFFFFFFFF); // Ensure positive hex value
48
49
        return 'e-bear-resource-' . $crcHex;
50
    }
51
}
52