Passed
Push — master ( 13ebde...538c8c )
by Stephen
05:08
created

Url::withParams()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sfneal\Dependencies\Utils;
4
5
class Url
6
{
7
    /**
8
     * @var string
9
     */
10
    protected $uri;
11
12
    /**
13
     * @var array
14
     */
15
    protected $params;
16
17
    /**
18
     * Static URL constructor.
19
     *
20
     * @param  string  $uri
21
     * @return self
22
     */
23
    public static function from(string $uri): self
24
    {
25
        return new self($uri);
26
    }
27
28
    /**
29
     * Add query parameters to a URL.
30
     *
31
     * @param  array|null  $params
32
     * @return $this
33
     */
34
    public function withParams(array $params = null): self
35
    {
36
        $this->params = $params;
37
38
        return $this;
39
    }
40
41
    /**
42
     * Url constructor.
43
     *
44
     * @param  string  $uri
45
     * @param  array|null  $params
46
     */
47
    public function __construct(string $uri, array $params = null)
48
    {
49
        $this->uri = $uri;
50
        $this->withParams($params);
51
    }
52
53
    /**
54
     * Retrieve a URL with params appended to the query string.
55
     *
56
     * @return string
57
     */
58
    public function get(): string
59
    {
60
        return self::generateUrl($this->uri).self::generateQueryString($this->params);
61
    }
62
63
    /**
64
     * Generate a URL.
65
     *
66
     * @param  string  $uri
67
     * @return string
68
     */
69
    protected static function generateUrl(string $uri): string
70
    {
71
        return 'https://'.$uri;
72
    }
73
74
    /**
75
     * Generate a query string.
76
     *
77
     * @param  array|null  $params
78
     * @return string
79
     */
80
    protected static function generateQueryString(array $params = null): string
81
    {
82
        if (! is_null($params)) {
83
            $query = '?';
84
85
            $paramStrings = [];
86
            foreach (array_unique($params) as $key => $value) {
87
                $paramStrings[] = "{$key}={$value}";
88
            }
89
90
            return $query.implode('&', $paramStrings);
91
        }
92
93
        return '';
94
    }
95
}
96