DevSemanticInvoker   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 19
c 1
b 0
f 1
dl 0
loc 42
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A invoke() 0 31 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource\SemanticLog;
6
7
use BEAR\Resource\AbstractRequest;
8
use BEAR\Resource\InvokerInterface;
9
use BEAR\Resource\ResourceObject;
10
use Koriym\SemanticLogger\DevLogger;
11
use Koriym\SemanticLogger\SemanticLoggerInterface;
12
use Override;
13
use Ray\Di\Di\Named;
14
use Throwable;
15
16
use function spl_object_hash;
17
18
/**
19
 * Development semantic invoker with log persistence for MCP integration
20
 *
21
 * Orchestrates semantic logging with immediate file persistence for AI-assisted debugging.
22
 * Follows single responsibility principle by delegating persistence to vendor DevLogger.
23
 */
24
final class DevSemanticInvoker implements InvokerInterface
25
{
26
    public function __construct(
27
        #[Named('original')]
28
        private InvokerInterface $invoker,
29
        private SemanticLoggerInterface $logger,
30
        private ContextFactoryInterface $factory,
31
        private DevLogger $devLogger,
32
    ) {
33
    }
34
35
    #[Override]
36
    public function invoke(AbstractRequest $request): ResourceObject
37
    {
38
        $openContext = $this->factory->createOpenContext($request);
39
        $openId = $this->logger->open($openContext);
40
41
        try {
42
            $result = $this->invoker->invoke($request);
43
            $closeContext = $this->factory->createCompleteContext($result, $openContext);
44
45
            try {
46
                $this->logger->close($closeContext, $openId);
47
            } catch (Throwable) {
48
                // Protect original result from being masked by close() failure
49
            }
50
51
            return $result;
52
        } catch (Throwable $e) {
53
            $exceptionId = 'e-' . spl_object_hash($e);
54
            $errorContext = $this->factory->createErrorContext($e, $exceptionId, $openContext);
55
56
            try {
57
                $this->logger->close($errorContext, $openId);
58
            } catch (Throwable) {
59
                // Protect original exception from being masked by close() failure
60
            }
61
62
            throw $e;
63
        } finally {
64
            // Persist logs once, regardless of success or failure
65
            $this->devLogger->log($this->logger);
66
        }
67
    }
68
}
69