2016-08-01 15:36:39 +03:00
|
|
|
<?php
|
2017-10-12 11:13:20 +03:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2017-07-16 10:28:40 +03:00
|
|
|
namespace Shlinkio\Shlink\Common;
|
2016-08-01 15:36:39 +03:00
|
|
|
|
2018-10-05 20:19:44 +03:00
|
|
|
use const JSON_ERROR_NONE;
|
2018-09-11 20:44:33 +03:00
|
|
|
use function getenv;
|
2018-10-05 19:52:42 +03:00
|
|
|
use function in_array;
|
2018-10-28 10:24:06 +03:00
|
|
|
use function json_decode as spl_json_decode;
|
2018-10-05 20:19:44 +03:00
|
|
|
use function json_last_error;
|
|
|
|
use function json_last_error_msg;
|
2018-09-11 20:44:33 +03:00
|
|
|
use function strtolower;
|
|
|
|
use function trim;
|
|
|
|
|
2017-07-16 10:28:40 +03:00
|
|
|
/**
|
|
|
|
* Gets the value of an environment variable. Supports boolean, empty and null.
|
|
|
|
* This is basically Laravel's env helper
|
|
|
|
*
|
|
|
|
* @param string $key
|
|
|
|
* @param mixed $default
|
|
|
|
* @return mixed
|
|
|
|
* @link https://github.com/laravel/framework/blob/5.2/src/Illuminate/Foundation/helpers.php#L369
|
|
|
|
*/
|
|
|
|
function env($key, $default = null)
|
|
|
|
{
|
|
|
|
$value = getenv($key);
|
|
|
|
if ($value === false) {
|
|
|
|
return $default;
|
|
|
|
}
|
2016-08-01 15:36:39 +03:00
|
|
|
|
2017-07-16 10:28:40 +03:00
|
|
|
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 null;
|
2016-08-01 15:36:39 +03:00
|
|
|
}
|
2017-07-16 10:28:40 +03:00
|
|
|
|
|
|
|
return trim($value);
|
2016-08-01 15:36:39 +03:00
|
|
|
}
|
2018-10-05 19:43:39 +03:00
|
|
|
|
2018-10-05 20:19:44 +03:00
|
|
|
function contains($needle, array $haystack): bool
|
2018-10-05 19:43:39 +03:00
|
|
|
{
|
2018-10-05 19:52:42 +03:00
|
|
|
return in_array($needle, $haystack, true);
|
2018-10-05 19:43:39 +03:00
|
|
|
}
|
2018-10-05 20:19:44 +03:00
|
|
|
|
2018-10-28 10:24:06 +03:00
|
|
|
/**
|
|
|
|
* @throws Exception\InvalidArgumentException
|
|
|
|
*/
|
2018-10-05 20:19:44 +03:00
|
|
|
function json_decode(string $json, int $depth = 512, int $options = 0): array
|
|
|
|
{
|
2018-10-28 10:24:06 +03:00
|
|
|
$data = spl_json_decode($json, true, $depth, $options);
|
2018-10-05 20:19:44 +03:00
|
|
|
if (JSON_ERROR_NONE !== json_last_error()) {
|
2018-10-28 10:24:06 +03:00
|
|
|
throw new Exception\InvalidArgumentException(sprintf('Error decoding JSON: %s', json_last_error_msg()));
|
2018-10-05 20:19:44 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
return $data;
|
|
|
|
}
|