Passed
Pull Request — master (#19)
by
unknown
04:48 queued 01:58
created

SetRequestIpMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 23
ccs 0
cts 10
cp 0
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A process() 0 17 4
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