PathResolver::makeRegExp()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 2
nop 1
dl 0
loc 15
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace PTS\PSR15\MiddlewareManager;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
7
class PathResolver
8
{
9
    /**
10
     * @param string $path
11
     * @param ServerRequestInterface $request
12
     *
13
     * @return bool
14
     */
15
    public function isMatch(string $path, ServerRequestInterface $request): bool
16
    {
17
        $regexp = $this->makeRegExp($path);
18
        return preg_match('~^'.$regexp.'$~Uiu', $request->getUri()->getPath(), $values) === 1;
19
    }
20
21
    public function makeRegExp(string $path): string
22
    {
23
        $regexp = $path;
24
        $placeholders = [];
25
26
        if (preg_match_all('~{(.*)}~Uu', $regexp, $placeholders)) {
27
            foreach ($placeholders[0] as $index => $match) {
28
                $name = $placeholders[1][$index];
29
                $replace = '[^\/]+';
30
                $replace = '(?<'.$name.'>' . $replace . ')';
31
                $regexp = str_replace($match, $replace, $regexp);
32
            }
33
        }
34
35
        return $regexp;
36
    }
37
}
38