Passed
Pull Request — 1.x (#334)
by Akihito
11:25
created

ResourceErrorContext::createExceptionId()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 12
rs 10
cc 4
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource\SemanticLog;
6
7
use Koriym\SemanticLogger\AbstractContext;
8
9
final class ResourceErrorContext extends AbstractContext
10
{
11
    /** @psalm-suppress InvalidClassConstantType */
12
    public const TYPE = 'bear_resource_error';
13
14
    /** @psalm-suppress InvalidClassConstantType */
15
    public const SCHEMA_URL = 'https://bearsunday.github.io/BEAR.Resource/schemas/bear-resource-error.json';
16
17
    public readonly string $exceptionId;
18
19
    public function __construct(
20
        public readonly string $exceptionClass,
21
        public readonly string $exceptionMessage,
22
        string $exceptionId = '',
23
    ) {
24
        $this->exceptionId = $exceptionId !== '' ? $exceptionId : $this->createExceptionId();
0 ignored issues
show
Bug introduced by
The property exceptionId is declared read-only in BEAR\Resource\SemanticLog\ResourceErrorContext.
Loading history...
25
    }
26
27
    private function createExceptionId(): string
28
    {
29
        $crc = crc32($this->exceptionClass);
30
        $crcHex = dechex($crc & 0xFFFFFFFF); // Ensure positive hex value
31
        
32
        // Use fixed ID in test environment for reproducible tests
33
        if (defined('PHPUNIT_COMPOSER_INSTALL') || (isset($GLOBALS['_composer_autoload_path']) && str_contains($GLOBALS['_composer_autoload_path'], 'phpunit'))) {
34
            static $counter = 0;
35
            return 'e-bear-resource-test-' . sprintf('%03d', ++$counter) . '-' . $crcHex;
36
        }
37
        
38
        return 'e-bear-resource-' . uniqid() . '-' . $crcHex;
39
    }
40
}
41