Passed
Push — master ( bf8e81...016379 )
by Vsevolods
06:13
created

AliasedPathPatternRouteCollection::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1.0156

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 4
cp 0.75
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1.0156
1
<?php declare(strict_types = 1);
2
3
namespace Venta\Routing;
4
5
use Venta\Contracts\Routing\MutableRouteCollection;
6
use Venta\Contracts\Routing\Route as RouteContract;
7
use Venta\Contracts\Routing\RouteGroup as RouteGroupContract;
8
9
/**
10
 * Class SugaredRouteCollection
11
 *
12
 * @package Venta\Routing
13
 */
14
class AliasedPathPatternRouteCollection implements MutableRouteCollection
15
{
16
17
    /**
18
     * @var MutableRouteCollection
19
     */
20
    private $routes;
21
22
    /**
23
     * SugaredRouteCollection constructor.
24
     *
25
     * @param MutableRouteCollection $routes
26
     */
27 2
    public function __construct(MutableRouteCollection $routes)
28
    {
29 2
        $this->routes = $routes;
30 2
    }
31
32
    /**
33
     * @inheritDoc
34
     */
35
    public function addGroup(RouteGroupContract $group): MutableRouteCollection
36
    {
37
        $this->routes->addGroup($group);
38
39
        return $this;
40
    }
41
42
    /**
43
     * @inheritDoc
44
     */
45 1
    public function addRoute(RouteContract $route): MutableRouteCollection
46
    {
47 1
        $this->routes->addRoute($route->withPath($this->replaceRegexAliases($route->getPath())));
48
49 1
        return $this;
50
    }
51
52
    /**
53
     * @inheritDoc
54
     */
55
    public function findByName(string $routeName)
56
    {
57
        return $this->routes->findByName($routeName);
58
    }
59
60
    /**
61
     * @inheritDoc
62
     */
63
    public function getRoutes(): array
64
    {
65
        return $this->routes->getRoutes();
66
    }
67
68
    /**
69
     * Returns aliases to replace. Overwrite this method to remove / add your aliases.
70
     *
71
     * @return array
72
     */
73 1
    protected function getRegexAliases(): array
74
    {
75
        return [
76 1
            '/{(.+?):number}/' => '{$1:[0-9]+}',
77
            '/{(.+?):word}/' => '{$1:[a-zA-Z]+}',
78
            '/{(.+?):alphanum}/' => '{$1:[a-zA-Z0-9-_]+}',
79
            '/{(.+?):slug}/' => '{$1:[a-z0-9-]+}',
80
        ];
81
    }
82
83
    /**
84
     * Replaces regex aliases within provided $path.
85
     *
86
     * @param string $path
87
     * @return string
88
     */
89 1
    private function replaceRegexAliases(string $path): string
90
    {
91 1
        $regexAliases = $this->getRegexAliases();
92
93 1
        return preg_replace(array_keys($regexAliases), array_values($regexAliases), $path);
94
    }
95
96
}