UrlHelper::to()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tebe\Pvc\Helper;
6
7
use InvalidArgumentException;
8
9
// @todo implement class properly
10
11
class UrlHelper
12
{
13
    /**
14
     * @param mixed $url
15
     * @return string
16
     * @throws InvalidArgumentException
17
     */
18
    public static function to($url = ''): string
19
    {
20
        if (is_array($url)) {
21
            return static::toRoute($url);
22
        }
23
        if (is_string($url)) {
24
            return $url;
25
        }
26
        throw new InvalidArgumentException('Only array or string allowed');
27
    }
28
29
    /**
30
     * @param array $route
31
     * @return string
32
     * @throws InvalidArgumentException
33
     */
34
    public static function toRoute(array $route): string
35
    {
36
        if (empty($route)) {
37
            throw new InvalidArgumentException('The given route is empty');
38
        }
39
40
        $urlParts = [$_SERVER['SCRIPT_NAME']];
41
42
        $r = trim(array_shift($route), '/');
43
        if (!empty($r)) {
44
            $urlParts[] = '/';
45
            $urlParts[] = $r;
46
        }
47
48
        $anchor = [];
49
        if (isset($route['#'])) {
50
            $anchor[] = '#';
51
            $anchor[] = $route['#'];
52
            unset($route['#']);
53
        }
54
55
        if (!empty($route)) {
56
            $query = http_build_query($route);
57
            $urlParts[] = '?';
58
            $urlParts[] = $query;
59
        }
60
61
        $urlParts = array_merge($urlParts, $anchor);
62
63
        $url = implode('', $urlParts);
64
        return $url;
65
    }
66
}
67