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

SetRequestIpMiddleware::process()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 17
ccs 0
cts 9
cp 0
crap 20
rs 10
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 extends Sentry scope with IP address of the request. Because PSR request is used, it takes trusted
17
 * proxies into account, which does not happen during automatic handling by PHP SDK.
18
 */
19
class SetRequestIpMiddleware implements MiddlewareInterface
20
{
21
    public function __construct(private ContainerInterface $container)
22
    {
23
    }
24
25
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
26
    {
27
        if ($this->container->has(HubInterface::class)) {
28
            /** @var HubInterface $sentry */
29
            $sentry = $this->container->get(HubInterface::class);
30
            $client = $sentry->getClient();
31
32
            if ($client !== null && $client->getOptions()->shouldSendDefaultPii()) {
33
                $sentry->configureScope(static function (Scope $scope) use ($request): void {
34
                    $scope->setUser([
35
                        'ip_address' => $request->getServerParams()['REMOTE_ADDR'] ?? null,
36
                    ]);
37
                });
38
            }
39
        }
40
41
        return $handler->handle($request);
42
    }
43
}
44