Passed
Push — master ( 2939ee...e672a8 )
by Enrico
02:30
created

UrlRewriter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 23
dl 0
loc 62
ccs 25
cts 25
cp 1
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A process() 0 24 4
A appyRules() 0 11 3
A __construct() 0 3 1
1
<?php
2
namespace LinkedDataCenter;
3
4
use Psr\Http\Message\ResponseInterface;
5
use Psr\Http\Message\ServerRequestInterface;
6
use Psr\Http\Server\RequestHandlerInterface;
7
use Psr\Http\Server\MiddlewareInterface;
8
use RuntimeException;
9
10
/**
11
 * This middleware rewrite urls using the rules in 'urlRewriting.rules' container parameter
12
 */
13
class UrlRewriter implements MiddlewareInterface
14
{ 
15
    
16
    /**
17
     * @var array of rules to be executed on Response uri
18
     */
19
    private $rules;
20
    
21
    
22
    /**
23
     * Configure the rewriting rules.
24
     */
25 5
    public function __construct(array $rules)
26
    {        
27 5
        $this->rules = $rules;
28 5
    }
29
    
30
    
31
    /**
32
     * Process a server request and return a response.
33
     */
34 5
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
35
    {
36 5
        $uri = $request->getUri();
37 5
        if ($scheme = $uri->getScheme()) { $scheme .= ':';}
38 5
        $authority = $uri->getAuthority();
39 5
        $path = $uri->getPath();
40 5
        if ($query = $uri->getQuery()) { $query = '?'.$query;};
41 5
        if ($fragment = $uri->getFragment()) { $fragment = '#'.$fragment;};
42
        
43
        // invariant part is not considered in match
44 5
        $invariantUriPart = "$scheme//$authority";
45
        
46
        // $matchSubject is the portion of the uri we are interest in
47 5
        $replacedUriPart=$this->appyRules($path.$query.$fragment);
48
        
49 5
        $parsedNewUrl = parse_url($invariantUriPart.$replacedUriPart );
50
        
51 5
        $request = $request->withUri(
52 5
            $uri->withPath($parsedNewUrl['path'] ?? '')
53 5
            ->withQuery($parsedNewUrl['query'] ?? '')
54 5
            ->withFragment($parsedNewUrl['fragment'] ?? '')
55
        );
56
        
57 5
        return $handler->handle($request);
58
    }
59
    
60
    
61
    /**
62
     * Apply all matching rules to a path.
63
     */
64 5
    private function appyRules(string $subject): string
65
    {
66 5
        foreach($this->rules as $pattern=>$replacement) {
67 5
            $pattern = '#^'. $pattern.'$#';
68 5
            $subject = preg_replace($pattern, $replacement, $subject);
69 5
            if( is_null($subject)){
70 5
                throw new RuntimeException("Bad replacement '$pattern', '$replacement'");
71
            }
72
        }
73
        
74 5
        return $subject;
75
    }
76
    
77
}