Passed
Pull Request — master (#19)
by
unknown
02:34
created

SetRequestIpMiddleware::process()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 19
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 3
nop 2
dl 0
loc 19
ccs 0
cts 9
cp 0
crap 20
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Sentry\Http;
6
7
use Psr\Container\ContainerInterface;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
use Sentry\State\HubInterface;
13
use Sentry\State\Scope;
14
15
/**
16
 * This middleware enriches the Sentry scope with the IP address of the request.
17
 * We do this ourself instead of letting the PHP SDK handle this because we want
18
 * the IP from the Psr request because it takes into account trusted proxies.
19
 */
20
class SetRequestIpMiddleware implements MiddlewareInterface
21
{
22
    public function __construct(private ContainerInterface $container)
23
    {
24
    }
25
26
    public function process(
27
        ServerRequestInterface $request,
28
        RequestHandlerInterface $handler
29
    ): ResponseInterface {
30
        if ($this->container->has(HubInterface::class)) {
31
            /** @var HubInterface $sentry */
32
            $sentry = $this->container->get(HubInterface::class);
33
            $client = $sentry->getClient();
34
35
            if ($client !== null && $client->getOptions()->shouldSendDefaultPii()) {
36
                $sentry->configureScope(static function (Scope $scope) use ($request): void {
37
                    $scope->setUser([
38
                        'ip_address' => $request->getServerParams()['REMOTE_ADDR'] ?? null,
39
                    ]);
40
                });
41
            }
42
        }
43
44
        return $handler->handle($request);
45
    }
46
}
47