UrlsWithPlaceholders   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 43
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getPlaceholders() 0 9 3
A replace() 0 7 2
A validValue() 0 9 2
A sanitizeValue() 0 3 1
1
<?php
2
3
4
namespace Apie\OpenapiSchema\ValueObjects;
5
6
use Apie\CommonValueObjects\Url;
7
use Apie\ValueObjects\StringTrait;
8
use Apie\ValueObjects\ValueObjectInterface;
9
10
class UrlsWithPlaceholders implements ValueObjectInterface
11
{
12
    use StringTrait;
13
14
    /**
15
     * @var string[]|null
16
     */
17
    private $placeholders;
18
19
    protected function validValue(string $value): bool
20
    {
21
        $identifier = '(\w|-|{\w+})+';
22
        $scheme = '^' . $identifier . '://';
23
        $username = $identifier . '(:' . $identifier . ')?';
24
        $hostname = $identifier . '(\.' . $identifier . ')*';
25
        $path = '/(.|{\w+})*';
26
        $regex = '#' . $scheme . '(' . $username . '@)?' . $hostname . '(' . $path . ')*$#i';
27
        return preg_match($regex, $value) ? true : false;
28
    }
29
30
    public function getPlaceholders()
31
    {
32
        if (null !== $this->placeholders) {
33
            return $this->placeholders;
34
        }
35
        if (preg_match_all('/{(\w+)}/', $this->value, $matches)) {
36
            return $this->placeholders = $matches[1];
37
        }
38
        return $this->placeholders = [];
39
    }
40
41
    public function replace(array $replacements): Url
42
    {
43
        $value = $this->value;
44
        foreach ($this->getPlaceholders() as $placeholder) {
45
            $value = str_replace('{' . $placeholder . '}', rawurlencode($replacements[$placeholder]), $value);
46
        }
47
        return new Url($value);
48
    }
49
50
    protected function sanitizeValue(string $value): string
51
    {
52
        return $value;
53
    }
54
}
55