Created
May 31, 2017 01:39
-
-
Save VictorHugoBatista/58e26d9167862a91d9c36dc86f7d1082 to your computer and use it in GitHub Desktop.
Framework simples para manipulação de variáveis de ambiente via arquivos '.ENV'. Depende do pacote vlucas/phpdotenv (https://github.com/vlucas/phpdotenv)
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 | |
namespace <VENDOR>\Environment; | |
use Dotenv\Dotenv; | |
/** | |
* Responsável pela manipulação de variáveis de ambiente. | |
* Tem o pacote 'vlucas/phpdotenv' como dependência. | |
* @see https://github.com/vlucas/phpdotenv | |
* @package GestaoEscolar\Environment | |
*/ | |
class DotEnvHandler | |
{ | |
/** | |
* Localização do arquivo '.env'. | |
* @var string | |
*/ | |
private $dotEnvPath; | |
/** | |
* Array contendo todas as variáveis de ambiente. | |
* @var array | |
*/ | |
private $env = []; | |
/** | |
* Lê arquivo '.ENV' e carrega as variáveis na propriedade $env. | |
* @param string $dotEnvPath Local do arquivo '.ENV'. | |
* @param bool $overload Se 'true', as variáveis encontradas sobreescrevem as variáveis do ambiente. Padrão: false. | |
*/ | |
public function __construct(string $dotEnvPath, bool $overload = false) | |
{ | |
$this->dotEnvPath = $dotEnvPath; | |
$dotEnv = new Dotenv($dotEnvPath); | |
if ($overload) { | |
$dotEnv->overload(); | |
} else { | |
$dotEnv->load(); | |
} | |
$this->env = $_ENV; | |
} | |
/** | |
* Retorna uma variável de ambiente. Caso não exista, retorna null. | |
* @param string $varName Nome da variável de ambiente à ser retornada. Case sensitive. | |
* @return mixed|null Variável de ambiente à ser retornada. | |
*/ | |
public function getEnvironmentVar(string $varName) | |
{ | |
return (array_key_exists($varName, $this->env)) ? $this->env[$varName] : null; | |
} | |
/** | |
* Retorna local do arquivo '.ENV' carregado. | |
* @return string Local do arquivo '.ENV' carregado. | |
*/ | |
public function getDotEnvPath() | |
{ | |
return $this->dotEnvPath; | |
} | |
/** | |
* Retorna conjunto das variáveis de ambiente carregadas. | |
* @return array Conjunto das variáveis de ambiente carregadas. | |
*/ | |
public function getEnv() | |
{ | |
return $this->env; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment