Skip to content

Instantly share code, notes, and snippets.

@deweller
Forked from mattstauffer/env.helper.php
Last active January 20, 2023 14:06
Show Gist options
  • Save deweller/5820432e4c89b0909c864c0aa36fa8e5 to your computer and use it in GitHub Desktop.
Save deweller/5820432e4c89b0909c864c0aa36fa8e5 to your computer and use it in GitHub Desktop.
Laravel's env() helper
<?php
/**
* Gets the value of an environment variable. Supports boolean, empty and null.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
function env($key, $default = null)
{
$value = getenv($key);
if ($value === false) {
return value($default);
}
switch (strtolower($value)) {
case "true":
case "(true)":
return true;
case "false":
case "(false)":
return false;
case "empty":
case "(empty)":
return "";
case "null":
case "(null)":
return;
}
if (startsWith($value, '"') && endsWith($value, '"')) {
return substr($value, 1, -1);
}
return $value;
}
/**
* Return the default value of the given value.
*
* @param mixed $value
* @return mixed
*/
function value($value, ...$args)
{
return $value instanceof Closure ? $value(...$args) : $value;
}
/**
* Determine if a given string starts with a given substring.
*
* @param string $haystack
* @param string|string[] $needles
* @return bool
*/
function startsWith($haystack, $needles)
{
foreach ((array) $needles as $needle) {
if ((string) $needle !== "" && str_starts_with($haystack, $needle)) {
return true;
}
}
return false;
}
/**
* Determine if a given string ends with a given substring.
*
* @param string $haystack
* @param string|string[] $needles
* @return bool
*/
function endsWith($haystack, $needles)
{
foreach ((array) $needles as $needle) {
if ((string) $needle !== "" && str_ends_with($haystack, $needle)) {
return true;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment