|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Kosv\RandomUser\Url; |
|
6
|
|
|
|
|
7
|
|
|
abstract class AbstractBuilder |
|
8
|
|
|
{ |
|
9
|
|
|
private const LIST_DELIMITER = ','; |
|
10
|
|
|
|
|
11
|
|
|
private string $host = ''; |
|
12
|
|
|
private string $path = ''; |
|
13
|
|
|
private array $params = []; |
|
14
|
|
|
private string $scheme = ''; |
|
15
|
|
|
|
|
16
|
|
|
public function build(): string |
|
17
|
|
|
{ |
|
18
|
|
|
$url = $this->scheme ? "{$this->scheme}://" : ''; |
|
19
|
|
|
$url .= $this->host; |
|
20
|
|
|
$url .= $this->path ? "/{$this->path}" : ''; |
|
21
|
|
|
|
|
22
|
|
|
$params = $this->buildParams($this->params); |
|
23
|
|
|
if ($params) { |
|
24
|
|
|
if (!$this->path) { |
|
25
|
|
|
$url .= '/'; |
|
26
|
|
|
} |
|
27
|
|
|
$url .= '?' . $params; |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
return $url; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
public function setHost(string $host) |
|
34
|
|
|
{ |
|
35
|
|
|
$this->host = $host; |
|
36
|
|
|
return $this; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public function setPath(string $path) |
|
40
|
|
|
{ |
|
41
|
|
|
$this->path = $path; |
|
42
|
|
|
return $this; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function setParam(string $name, array $vals) |
|
46
|
|
|
{ |
|
47
|
|
|
if (isset($this->params[$name]) && !count($vals)) { |
|
48
|
|
|
unset($this->params[$name]); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
$this->params[$name] = $vals; |
|
52
|
|
|
|
|
53
|
|
|
return $this; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function setScheme(string $scheme) |
|
57
|
|
|
{ |
|
58
|
|
|
$this->scheme = $scheme; |
|
59
|
|
|
return $this; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
private function buildParams(array $params): string |
|
63
|
|
|
{ |
|
64
|
|
|
$params = array_filter($params, function ($v): bool { |
|
65
|
|
|
return !empty($v); |
|
66
|
|
|
}, \ARRAY_FILTER_USE_BOTH); |
|
67
|
|
|
|
|
68
|
|
|
return implode('&', array_map(function ($k, $v): string { |
|
69
|
|
|
return $k . '=' . implode(self::LIST_DELIMITER, $v); |
|
70
|
|
|
}, array_keys($params), $params)); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|