Passed
Push — master ( 65ba04...698d84 )
by Ben
01:03 queued 11s
created

Url::assembleScheme()   A

Complexity

Conditions 5
Paths 12

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 5

Importance

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