UrlsWithPlaceholders::getPlaceholders()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 9
rs 10
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