Passed
Push — master ( 84a0c3...19f789 )
by Arthur
02:17
created

UrlUtils::generateRelativeUrlFromPath()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 9
nc 10
nop 2
dl 0
loc 15
rs 8.2222
c 0
b 0
f 0
1
<?php
2
3
namespace WebThumbnailer\Utils;
4
5
/**
6
 * Class UrlUtils
7
 *
8
 * Util class for operations on URL strings.
9
 *
10
 * @package WebThumbnailer\Utils
11
 */
12
class UrlUtils
13
{
14
    /**
15
     * Extract the domains from an URL.
16
     *
17
     * @param string $url Given URL.
18
     *
19
     * @return string Extracted domains, lowercase.
20
     */
21
    public static function getDomain($url)
22
    {
23
        if (! parse_url($url, PHP_URL_SCHEME)) {
24
            $url = 'http://' . $url;
25
        }
26
        return strtolower(parse_url($url, PHP_URL_HOST));
27
    }
28
29
    /**
30
     * Generate a relative URL from absolute local path.
31
     * Example:
32
     *    - /home/website/resources/file.txt
33
     *    ====>
34
     *    - resources/file.txt
35
     *
36
     * @param array  $server $_SERVER array.
37
     * @param string $path   Absolute path to transform.
38
     *
39
     * @return string Relative path.
40
     */
41
    public static function generateRelativeUrlFromPath($server, $path)
42
    {
43
        if (isset($server['CONTEXT_DOCUMENT_ROOT'])) {
44
            $root = ! empty($server['CONTEXT_DOCUMENT_ROOT']) ? rtrim($server['CONTEXT_DOCUMENT_ROOT'], '/') .'/' : '';
45
            $path = substr($path, strlen($root));
46
        } elseif (isset($server['DOCUMENT_ROOT'])) {
47
            $root = ! empty($server['DOCUMENT_ROOT']) ? rtrim($server['DOCUMENT_ROOT'], '/') .'/' : '';
48
            $path = substr($path, strlen($root));
49
        }
50
51
        if (isset($server['SCRIPT_NAME']) && preg_match('#/?(.+/)\w+\.php$#', $server['SCRIPT_NAME'], $matches) > 0) {
52
            $path = substr($path, strlen($matches[1]));
53
        }
54
55
        return $path;
56
    }
57
58
    /**
59
     * Retrieve the file extension from a URL.
60
     *
61
     * @param string $url given URL.
62
     *
63
     * @return string|bool File extension or false if not found.
64
     */
65
    public static function getUrlFileExtension($url)
66
    {
67
        $path = parse_url($url, PHP_URL_PATH);
68
        if (preg_match('/\.(\w+)$/i', $path, $match) > 0) {
69
            return strtolower($match[1]);
70
        }
71
        return '';
72
    }
73
}
74