Passed
Push — main ( ef112d...d39948 )
by Pieter
03:42
created

UrlsWithPlaceholders::replace()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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