Lines 100.00% 14 / 14
Functions and Methods 100.00% 7 / 7
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
LogOrigin 100.00% 14 / 14 100.00% 7 / 7 10 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 broker 100.00% 1 / 1 100.00% 1 / 1 1
 forScope 100.00% 1 / 1 100.00% 1 / 1 1
 forApp 100.00% 1 / 1 100.00% 1 / 1 1
 forWorkerOutput 100.00% 1 / 1 100.00% 1 / 1 1
 findInContext 100.00% 2 / 2 100.00% 1 / 1 2
 relabelTracedRecord 100.00% 7 / 7 100.00% 1 / 1 3
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Logging;
6
7use Stewart\Contracts\App\AppId;
8use Stewart\Runtime\Model\ResourceScope;
9use Stewart\Runtime\Model\WorkerId;
10
11final readonly class LogOrigin
12{
13    public const string CONTEXT_KEY = 'stewartLogOrigin';
14
15    public const string SOURCE_KEY = 'source';
16
17    public const string TRACE_KEY = 'stewartTrace';
18
19    private const string TRACE_LEVEL_NAME = 'TRACE';
20
21    private function __construct(
22        public string $label,
23        public ?ResourceScope $scope,
24        public bool $traced = false,
25    ) {}
26
27    public static function broker(): self
28    {
29        return new self('broker', null);
30    }
31
32    public static function forScope(ResourceScope $scope, bool $traced = false): self
33    {
34        return new self($scope->wireValue(), $scope, $traced);
35    }
36
37    public static function forApp(AppId $appId): self
38    {
39        return self::forScope(ResourceScope::forApp($appId));
40    }
41
42    public static function forWorkerOutput(WorkerId $workerId): self
43    {
44        return new self('worker ' . $workerId->value, null);
45    }
46
47    /** @param array<mixed> $context */
48    public static function findInContext(array $context): ?self
49    {
50        $origin = $context[self::CONTEXT_KEY] ?? null;
51
52        return $origin instanceof self ? $origin : null;
53    }
54
55    // A trace record stays a debug record for Monolog; only its printed level name differs.
56    /**
57     * @template TValue
58     * @param array<TValue> $normalized
59     * @return array<TValue|string|array<mixed>>
60     */
61    public static function relabelTracedRecord(array $normalized): array
62    {
63        $extra = $normalized['extra'] ?? null;
64
65        if (!\is_array($extra) || !\array_key_exists(self::TRACE_KEY, $extra)) {
66            return $normalized;
67        }
68
69        unset($extra[self::TRACE_KEY]);
70        $normalized['extra'] = $extra;
71        $normalized['level_name'] = self::TRACE_LEVEL_NAME;
72
73        return $normalized;
74    }
75}