Completed
Pull Request — master (#1)
by Ben
02:08
created

Url::reassembleWithoutRoot()   A

Complexity

Conditions 5
Paths 16

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 6
nc 16
nop 0
dl 0
loc 13
ccs 6
cts 6
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
namespace Thinktomorrow\Url;
4
5
class Url
6
{
7
    /** @var ParsedUrl */
8
    private $parsedUrl;
9
10
    private function __construct(ParsedUrl $parsedUrl)
11
    {
12
        $this->parsedUrl = $parsedUrl;
13
    }
14
15
    public static function fromString(string $url)
16
    {
17
        return new static( ParsedUrl::fromString($url) );
18
    }
19
20
    public function setCustomRoot(Root $root)
21
    {
22 17
        $this->parsedUrl = $this->parsedUrl->replaceRoot($root);
23
24 17
        return $this;
25 16
    }
26
27 17
    public function secure()
28
    {
29 17
        return $this->scheme(true);
30
    }
31
32 3
    public function nonSecure()
33
    {
34 3
        return $this->scheme(false);
35
    }
36 3
37
    private function scheme(bool $secure = true)
38
    {
39 3
        $this->parsedUrl = $this->parsedUrl->replaceScheme($secure ? 'https' : 'http');
40
41 3
        return $this;
42
    }
43
44 2
    public function get()
45
    {
46 2
        return $this->parsedUrl->get();
47
    }
48
49 5
    public function isAbsolute(): bool
50
    {
51 5
        return $this->parsedUrl->hasHost();
52 5
    }
53
54 5
    public function localize(string $localeSegment = null, array $available_locales = [])
55
    {
56
        $localizedPath = str_replace('//', '/',
57 14
            rtrim('/'.trim($localeSegment.$this->delocalizePath($available_locales), '/'), '/')
58
        );
59 14
60 3
        $this->parsedUrl = $this->parsedUrl->replacePath($localizedPath);
61 1
62
        return $this;
63
    }
64
65 3
    private function delocalizePath(array $available_locales)
66
    {
67 3
        if (!$this->parsedUrl->hasPath()) {
68 1
            return;
69
        }
70
71 3
        $path_segments = explode('/', trim($this->parsedUrl->path(), '/'));
72
73
        // Remove the locale segment if present
74 11
        if (in_array($path_segments[0], array_keys($available_locales))) {
75
            unset($path_segments[0]);
76
        }
77 1
78
        return '/'.implode('/', $path_segments);
79 1
    }
80
81
    public function __toString(): string
82 8
    {
83
        return $this->get();
84 8
    }
85
}
86