Test Setup Failed
Push — master ( d1bf52...dc45f2 )
by Mehmet
02:56
created

GetUrl::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 5
nc 1
nop 4
1
<?php
2
declare(strict_types=1);
3
4
namespace Selami\View\Twig\Functions;
5
6
use Selami\View\FunctionInterface;
7
8
class GetUrl implements FunctionInterface
9
{
10
    private $aliases;
11
    private $alias;
12
    private $baseUrl;
13
    private $params;
14
15
    public function __construct(string $baseUrl, array $aliases, string $alias, array $params = [])
16
    {
17
        $this->aliases = $aliases;
18
        $this->alias = $alias;
19
        $this->params = $params;
20
        $this->baseUrl = $baseUrl;
21
    }
22
23
    public function run() : string
24
    {
25
        if (array_key_exists($this->alias, $this->aliases)) {
26
            return $this->findAlias();
27
        }
28
        return '';
29
    }
30
31
    private function findAlias() : string
32
    {
33
        $relativePath = $this->aliases[$this->alias];
34
        foreach ($this->params as $param => $value) {
35
            $relativePath = $this->findRelativePath($relativePath, $param, $value);
36
        }
37
        return $this->baseUrl . '/' . $relativePath;
38
    }
39
40
    private function findRelativePath($relativePath, $param, $value): string
41
    {
42
        if (strpos($param, ':') === strlen($param)-1) {
43
            return preg_replace('/{'.$param.'(.*?)}/msi', $value, $relativePath);
44
        }
45
        return str_replace('{'.$param.'}', $value, $relativePath);
46
    }
47
}
48