torrentpier/src/Env.php
Roman Kelesidis fad09cf0eb
Updated copyright year (#1201)
* Updated copyright year

* Updated
2023-12-12 22:14:01 +07:00

117 lines
2.8 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* TorrentPier Bull-powered BitTorrent tracker engine
*
* @copyright Copyright (c) 2005-2024 TorrentPier (https://torrentpier.com)
* @link https://github.com/torrentpier/torrentpier for the canonical source repository
* @license https://github.com/torrentpier/torrentpier/blob/master/LICENSE MIT License
*/
namespace TorrentPier;
use Closure;
use Dotenv\Repository\Adapter\PutenvAdapter;
use Dotenv\Repository\RepositoryBuilder;
use Dotenv\Repository\RepositoryInterface;
use PhpOption\Option;
/**
* Class Env
* @package TorrentPier
*/
class Env
{
/**
* Indicates if the putenv adapter is enabled.
*
* @var bool
*/
protected static bool $putenv = true;
/**
* The environment repository instance.
*
* @var RepositoryInterface|null
*/
protected static $repository;
/**
* Enable the putenv adapter.
*
* @return void
*/
public static function enablePutenv(): void
{
static::$putenv = true;
static::$repository = null;
}
/**
* Disable the putenv adapter.
*
* @return void
*/
public static function disablePutenv(): void
{
static::$putenv = false;
static::$repository = null;
}
/**
* Get the environment repository instance.
*
* @return RepositoryInterface
*/
public static function getRepository(): ?RepositoryInterface
{
if (static::$repository === null) {
$builder = RepositoryBuilder::createWithDefaultAdapters();
if (static::$putenv) {
$builder = $builder->addAdapter(PutenvAdapter::class);
}
static::$repository = $builder->immutable()->make();
}
return static::$repository;
}
/**
* Gets the value of an environment variable.
*
* @param string $key
* @param mixed $default
* @return mixed
*/
public static function get(string $key, $default = null)
{
return Option::fromValue(static::getRepository()->get($key))
->map(function ($value) {
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;
}
if (preg_match('/\A([\'"])(.*)\1\z/', $value, $matches)) {
return $matches[2];
}
return $value;
})
->getOrCall(fn () => $default instanceof Closure ? $default() : $default);
}
}