Created
January 18, 2017 14:49
-
-
Save orobogenius/da0f59813936ccf7ee70a5369899ce3b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//As would be defined in bootstrap.php | |
defined('HOST_NAME') OR define('HOST_NAME', $SERVER['SERVER_NAME']); | |
if (!function_exists('asset')) { | |
/** | |
* Generate an asset path | |
* | |
* @param string $path | |
* @param bool $secure | |
* @return string | |
*/ | |
function asset($path, $isSecure = null) | |
{ | |
if (urlValid($path)) { | |
return $path; | |
} | |
//Get the http scheme | |
$scheme = getScheme($isSecure); | |
return $scheme . HOST_NAME . '/public/' . $path; | |
} | |
} | |
if (!function_exists('url')) { | |
/** | |
* Generate an absolute URL to the given path. | |
* | |
* @param string $path | |
* @param bool|null $isSecure | |
* @return string | |
*/ | |
function url($path, $isSecure = null) | |
{ | |
//First, let's see if the path is a valid url, if it is, we just return it | |
if (urlValid($path)) { | |
return $path; | |
} | |
//Get the http scheme | |
$scheme = getScheme($isSecure); | |
//Check if this path has query params | |
if (($pos = strpos($path, '?')) !== false) { | |
//Path does have query params | |
$query = substr($path, $pos); | |
$path = substr($path, 0, $pos); | |
} else { | |
//Nope, no queries | |
$query = ''; | |
} | |
return $scheme . HOST_NAME . '/public/' . $path . $query; | |
} | |
} | |
/** | |
* Gets the http scheme of the url. | |
* | |
* @param bool|null $isSecure | |
* @return string | |
*/ | |
function getScheme($isSecure = null) | |
{ | |
$scheme = ''; | |
if (!is_null($isSecure) && $isSecure) { | |
//It's secure, let's take their word for it | |
$scheme = 'https://'; | |
} else { | |
//Looks like we'll have to find ourselves | |
$scheme = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ? 'https://' : 'http://'; | |
} | |
return $scheme; | |
} | |
/** | |
* Checks if the given url is valid | |
* | |
* @param string $path | |
* @return bool | |
*/ | |
function urlValid($path) | |
{ | |
$isUrlValid = false; | |
if (preg_match('/^(http:\/\/|https:\/\/|tel:|mailto:|#)/'), $path) { | |
$isUrlValid = true; | |
} | |
$isUrlValid = filter_var($path, FILTER_VALIDATE_URL) === true ? true : false; | |
return $isUrlValid; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment