HttpClientWrapper::setOpenTransaction()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace TechDeCo\ElasticApmAgent\Convenience\HttplugHttpClient;
5
6
use Exception;
7
use Http\Client\Exception as ClientException;
8
use Http\Client\HttpClient;
9
use Psr\Http\Message\RequestInterface;
10
use Psr\Http\Message\ResponseInterface;
11
use TechDeCo\ElasticApmAgent\Convenience\OpenTransaction;
12
use TechDeCo\ElasticApmAgent\Convenience\OpenTransactionEnricher;
13
use TechDeCo\ElasticApmAgent\Convenience\Util\Stopwatch;
14
use TechDeCo\ElasticApmAgent\Message\Span;
15
use function sprintf;
16
17
final class HttpClientWrapper implements HttpClient, OpenTransactionEnricher
18
{
19
    public const CORRELATION_ID_HEADER = 'X-Correlation-ID';
20
21
    /**
22
     * @var HttpClient
23
     */
24
    private $client;
25
26
    /**
27
     * @var OpenTransaction
28
     */
29
    private $transaction;
30
31 6
    public function __construct(HttpClient $client)
32
    {
33 6
        $this->client = $client;
34 6
    }
35
36 6
    public function setOpenTransaction(OpenTransaction $transaction): void
37
    {
38 6
        $this->transaction = $transaction;
39 6
    }
40
41
    /**
42
     * @throws ClientException
43
     * @throws Exception
44
     */
45 6
    public function sendRequest(RequestInterface $request): ResponseInterface
46
    {
47 6
        $start  = Stopwatch::start();
48 6
        $offset = $this->transaction->getStartOffset();
49
50
        try {
51 6
            $request = $request->withAddedHeader(
0 ignored issues
show
Coding Style introduced by
Consider using a different name than the parameter $request. This often makes code more readable.
Loading history...
52 6
                self::CORRELATION_ID_HEADER,
53 6
                $this->transaction->getCorrelationId()->toString()
54
            );
55
56 6
            return $this->client->sendRequest($request);
57
        } finally {
58 6
            $this->transaction->addSpan(new Span(
59 6
                Stopwatch::stop($start),
60 6
                sprintf('%s %s', $request->getMethod(), $request->getUri()->__toString()),
61 6
                $offset,
62 6
                'http.request'
63
            ));
64
        }
65
    }
66
}
67