Passed
Push — master ( 0fa97a...3e03bc )
by Felipe
02:17
created

PregMatchRequestTargetMiddleware::process()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of coisa/http.
4
 *
5
 * (c) Felipe Sayão Lobato Abreu <[email protected]>
6
 *
7
 * This source file is subject to the license that is bundled
8
 * with this source code in the file LICENSE.
9
 */
10
11
namespace CoiSA\Http\Middleware;
12
13
use Psr\Http\Message\ResponseInterface;
14
use Psr\Http\Message\ServerRequestInterface;
15
use Psr\Http\Server\MiddlewareInterface;
16
use Psr\Http\Server\RequestHandlerInterface;
17
18
/**
19
 * Class PregMatchRequestTargetMiddleware
20
 *
21
 * @package CoiSA\Http\Middleware
22
 */
23
final class PregMatchRequestTargetMiddleware implements MiddlewareInterface
24
{
25
    /**
26
     * @var string
27
     */
28
    private $pattern;
29
30
    /**
31
     * @var RequestHandlerInterface
32
     */
33
    private $handler;
34
35
    /**
36
     * PregMatchRequestTargetMiddleware constructor.
37
     *
38
     * @param string                  $pattern
39
     * @param RequestHandlerInterface $handler
40
     */
41
    public function __construct(string $pattern, RequestHandlerInterface $handler)
42
    {
43
        $this->pattern = '(' . $pattern . ')i';
44
        $this->handler = $handler;
45
    }
46
47
    /**
48
     * @param ServerRequestInterface  $request
49
     * @param RequestHandlerInterface $handler
50
     *
51
     * @return ResponseInterface
52
     */
53
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
54
    {
55
        if (!\preg_match($this->pattern, $request->getRequestTarget(), $matches)) {
56
            return $handler->handle($request);
57
        }
58
59
        return $this->handler->handle($request->withAttribute(self::class, $matches));
60
    }
61
}
62