Passed
Pull Request — master (#19)
by
unknown
04:36 queued 02:12
created

SetRequestIpMiddleware   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
eloc 11
dl 0
loc 31
ccs 0
cts 11
cp 0
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A process() 0 19 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 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
    /**
23
     * @var ContainerInterface
24
     */
25
    private $container;
26
27
    public function __construct(ContainerInterface $container)
28
    {
29
        $this->container = $container;
30
    }
31
32
    public function process(
33
        ServerRequestInterface $request,
34
        RequestHandlerInterface $handler
35
    ): ResponseInterface {
36
        if ($this->container->has(HubInterface::class)) {
37
            /** @var HubInterface $sentry */
38
            $sentry = $this->container->get(HubInterface::class);
39
            $client = $sentry->getClient();
40
41
            if ($client !== null && $client->getOptions()->shouldSendDefaultPii()) {
42
                $sentry->configureScope(static function (Scope $scope) use ($request): void {
43
                    $scope->setUser([
44
                        'ip_address' => $request->getServerParams()['REMOTE_ADDR'] ?? null,
45
                    ]);
46
                });
47
            }
48
        }
49
50
        return $handler->handle($request);
51
    }
52
}
53