/LoadEnv.php
PHP | 178 lines | 138 code | 30 blank | 10 comment | 13 complexity | cd6f0f93053107ae742934f24c815dc9 MD5 | raw file
- <?php
- /**
- * Created by PhpStorm.
- * User: marti
- * Date: 07-Mar-18
- * Time: 10:34
- */
- namespace Bootstrap;
- trait LoadEnv
- {
- protected $_env;
- public function __construct($env)
- {
- $this->_env = $env;
- }
- public function loadEnvironment()
- {
- $lines =$this->readLinesFromFile();
- foreach($lines as $line){
- if(!$this->isComment($line) && $this->looksLikeSetter($line)){
- $this->setEnvironmentVariable($line);
- }
- }
- return $lines;
- }
- protected function readLinesFromFile()
- {
- // Read file into an array of lines with auto-detected line endings
- $autodetect = ini_get('auto_detect_line_endings');
- ini_set('auto_detect_line_endings', '1');
- $lines = file($this->_env, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
- ini_set('auto_detect_line_endings', $autodetect);
- return $lines;
- }
- protected function isComment($line)
- {
- return strpos(ltrim($line), '#') === 0;
- }
- protected function looksLikeSetter($line)
- {
- return strpos($line, "=") !== false;
- }
- public function setEnvironmentVariable($name, $value = null)
- {
- list($name, $value) = $this->normaliseVariable($name, $value);
- // If PHP is running as an Apache module and an existing
- // Apache environment variable exists, overwrite it
- if (function_exists('apache_getenv') && function_exists('apache_setenv') && apache_getenv($name)) {
- apache_setenv($name, $value);
- }
- if (function_exists('putenv')) {
- setenv($name, $value);
- }
- $_ENV[$name] = $value;
- $_SERVER[$name] = $value;
- }
- protected function normaliseVariable($name, $value)
- {
- list($name, $value) = $this->splitCompoundStringIntoParts($name, $value);
- list($name, $value) = $this->sanitiseVariableName($name, $value);
- list($name, $value) = $this->sanitiseVariableValue($name, $value);
- $value = $this->resolveNestedVariables($value);
- return array($name, $value);
- }
- protected function resolveNestedVariables($value)
- {
- if(strpos($value, '$') !== false){
- $loader = $this;
- $value = preg_replace_callback(
- '/\${([a-zA-Z0-9_]+)}/',
- function($matchedPatterns) use($loader){
- $nestedVariable = $loader->getEnvirenmentVariable($matchedPatterns[1]);
- if($nestedVariable === null){
- return $matchedPatterns[0];
- }else{
- return $nestedVariable;
- }
- },
- $value
- );
- }
- return $value;
- }
- public function getEnvironmentVariable($name)
- {
- switch(true){
- case array_key_exists($name, $_ENV):
- return $_ENV[$name];
- case array_key_exists($name, $_SERVER):
- return $_SERVER[$name];
- default:
- $value = getenv($name);
- return $value === false ? null : $value;
- }
- }
- protected function splitCompoundStringIntoParts($name, $value)
- {
- if(strpos($name, '=') !== false){
- list($name, $value) = array_map('trim', explode('=', $name, 2));
- }
- return array($name, $value);
- }
- protected function sanitiseVariableName($name, $value)
- {
- $name = trim(str_replace(['export', '\'', '"'], '', $name));
- return array($name, $value);
- }
- protected function sanitiseVariableValue($name, $value)
- {
- $value = trim($value);
- if (!$value) {
- return array($name, $value);
- }
- if ($this->beginsWithAQuote($value)) { // value starts with a quote
- $quote = $value[0];
- $regexPattern = sprintf(
- '/^
- %1$s # match a quote at the start of the value
- ( # capturing sub-pattern used
- (?: # we do not need to capture this
- [^%1$s\\\\] # any character other than a quote or backslash
- |\\\\\\\\ # or two backslashes together
- |\\\\%1$s # or an escaped quote e.g \"
- )* # as many characters that match the previous rules
- ) # end of the capturing sub-pattern
- %1$s # and the closing quote
- .*$ # and discard any string after the closing quote
- /mx',
- $quote
- );
- $value = preg_replace($regexPattern, '$1', $value);
- $value = str_replace("\\$quote", $quote, $value);
- $value = str_replace('\\\\', '\\', $value);
- } else {
- $parts = explode(' #', $value, 2);
- $value = trim($parts[0]);
- // Unquoted values cannot contain whitespace
- if (preg_match('/\s+/', $value) > 0) {
- throw new \Exception('Dotenv values containing spaces must be surrounded by quotes.');
- }
- }
- return array($name, trim($value));
- }
- protected function beginsWithAQuote($value)
- {
- return strpbrk($value[0], '"\'') !== false;
- }
- }