Passed
Branch 2.0 (72e182)
by Philippe
02:18
created

UrlParser::set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Thinktomorrow\Locale\Parsers;
4
5
use Illuminate\Routing\UrlGenerator;
6
use Thinktomorrow\Locale\Values\Root;
7
use Thinktomorrow\Locale\Values\Url;
8
9
class UrlParser
10
{
11
    /** @var Url */
12
    private $url;
13
14
    /** @var string */
15
    private $localeSegment = null;
16
17
    /** @var array */
18
    private $available_locales = [];
19
20
    /** @var bool */
21
    private $secure;
22
23
    /** @var array */
24
    private $parameters = [];
25
26
    /** @var UrlGenerator */
27
    private $generator;
28
29 62
    public function __construct(UrlGenerator $generator)
30
    {
31 62
        $this->generator = $generator;
32
33
        /**
34
         * Default url is the root as given by the application
35
         */
36 62
        $this->url = $this->rootFromApplication();
37 62
    }
38
39 52
    public function get(): string
40
    {
41 52
        if(is_bool($this->secure)) $this->url->secure($this->secure);
42
43 52
        return $this->generator->to(
44 52
            $this->url->localize($this->localeSegment, $this->available_locales)->get(), $this->parameters, $this->secure
45
        );
46
    }
47
48 52
    public function set(string $url): self
49
    {
50 52
        $this->url = Url::fromString($url);
51
52 51
        return $this;
53
    }
54
55 8
    public function setCustomRoot(Root $root)
56
    {
57 8
        $this->url->setCustomRoot($root);
58
59 8
        return $this;
60
    }
61
62 50
    public function localize(string $localeSegment = null, array $available_locales): self
63
    {
64 50
        $this->localeSegment = $localeSegment;
65 50
        $this->available_locales = $available_locales;
66
67 50
        return $this;
68
    }
69
70 10
    public function parameters(array $parameters = []): self
71
    {
72 10
        $this->parameters = $parameters;
73
74 10
        return $this;
75
    }
76
77 40
    public function secure($secure = true): self
78
    {
79 40
        $this->secure = (bool) $secure;
80
81 40
        return $this;
82
    }
83
84 62
    private function rootFromApplication(): Url
85
    {
86 62
        return Url::fromString($this->generator->formatRoot($this->generator->formatScheme($this->secure)));
87
    }
88
89
    /**
90
     * Resolve the route via the Illuminate UrlGenerator.
91
92
     * @param $routekey
93
     * @param array $parameters
94
     *
95
     * @return string
96
     */
97 32
    public function resolveRoute($routekey, $parameters = [])
98
    {
99 32
        return $this->generator->route($routekey, $parameters, true);
100
    }
101
}
102