Completed
Push — master ( fdbf92...450a2e )
by Alxarafe
23:38 queued 08:30
created

baseUrl()   B

Complexity

Conditions 7
Paths 32

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 7.0671

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 32
nop 1
dl 0
loc 17
ccs 8
cts 9
cp 0.8889
crap 7.0671
rs 8.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * Alxarafe. Development of PHP applications in a flash!
4
 * Copyright (C) 2018-2019 Alxarafe <[email protected]>
5
 */
6
7
if (!defined('BASE_PATH')) {
8
    /**
9
     * Base path for the app.
10
     */
11
    define('BASE_PATH', realpath(__DIR__ . constant('DIRECTORY_SEPARATOR') . '..' . constant('DIRECTORY_SEPARATOR') . '..' . constant('DIRECTORY_SEPARATOR') . '..'));
12
}
13
14
if (!function_exists('basePath')) {
15
    /**
16
     * Returns the app base path.
17
     *
18
     * @param string $path
19
     *
20
     * @return string
21
     */
22
    function basePath(string $path = ''): string
23
    {
24 17
        return realpath(constant('BASE_PATH')) .
25
            (empty($path) ? $path : constant('DIRECTORY_SEPARATOR') . trim($path, constant('DIRECTORY_SEPARATOR')));
26
    }
27
}
28
29
if (!function_exists('redirect')) {
30
    /**
31
     * Redirects to path.
32
     *
33
     * @param string $path
34
     */
35
    function redirect(string $path)
36
    {
37
        header('Location: ' . $path);
38
    }
39
}
40
41
if (!function_exists('baseUrl')) {
42
    /**
43
     * Returns the base url.
44
     *
45
     * @param string $url
46
     *
47
     * @return string
48
     */
49
    function baseUrl(string $url = ''): string
50 2
    {
51 2
        $defaultPort = constant('SERVER_PORT') ?? 80;
52 2
        $defaultHost = constant('SERVER_NAME') ?? 'localhost';
53 2
        $path = $_SERVER['PHP_SELF'];
54 2
        // For PHPUnit tests, $_SERVER['PHP_SELF'] = 'vendor/bin/phpunit'
55
        if (isset($_SERVER['argv']) && $_SERVER['PHP_SELF'] === $_SERVER['argv'][0]) {
56
            $path = '';
57 2
        }
58 2
        $folder = str_replace(['/index.php', constant('APP_URI')], '', $path);
59
        $port = '';
60 2
        if (!in_array($defaultPort, ['80', '443'], false)) {
61
            $port = ':' . $defaultPort;
62
        }
63
        $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http')
64
            . '://' . $defaultHost . $port . constant('APP_URI') . $folder;
65
        return empty($url) ? $baseUrl : $baseUrl . '/' . trim($url, '/');
66
    }
67
}
68