Support double-quote in ENV values

2.x 1.0.1
Julien Rosset 4 years ago
parent a2565e945f
commit 9c6e619b7a

@ -38,6 +38,57 @@ abstract class BaseEnv {
$this->properties = array_change_key_case($this->initProperties(), CASE_UPPER);
$this->readEnv();
}
/**
* Initialize initial properties
*
* @return string[] Properties initial values (<property name> => <property value>)
*/
protected function initProperties (): array {
return [
'APP_DEV' => 0,
];
}
/**
* Read the ENV file
*
* @throws Exception If ENV can't be read
*/
private function readEnv (): void {
if (!file_exists(static::PATH_ENV)) {
return;
}
$lines = file(static::PATH_ENV, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
throw new Exception('Unable to read environment file "' . static::PATH_ENV . '"');
}
foreach ($lines as $line) {
if (preg_match('/^\s*(?:(?<comment>#).*|(?<key>[a-zA-Z0-9_-]+)=(?<value>.+?))$/i', $line, $match) !== 1) {
continue; // Ligne invalide
}
if (isset($match['comment']) && trim($match['comment']) !== '') {
continue; // Commentaire
}
if (preg_match('/^"(?<payload>.+)(?<!(?<!\\\\)\\\\)"$/', $match['value'], $matchValue) === 1) {
$match['value'] = preg_replace(
[
'/(?<!\\\\)\\\\"/',
'/\\\\\\\\/',
],
[
'"',
'\\',
],
$matchValue['payload']
);
}
$this->properties[mb_strtoupper($match['key'])] = $match['value'];
}
}
/**
* Get all properties
*
@ -78,6 +129,7 @@ abstract class BaseEnv {
return $this->properties[$name];
}
/**
* Get a property value as a boolean
*
@ -195,41 +247,4 @@ abstract class BaseEnv {
return $value;
}
/**
* Initialize initial properties
*
* @return string[] Properties initial values (&lt;property name&gt; => &lt;property value&gt;)
*/
protected function initProperties (): array {
return [
'APP_DEV' => 0,
];
}
/**
* Read the ENV file
*
* @throws Exception If ENV can't be read
*/
private function readEnv (): void {
if (!file_exists(static::PATH_ENV)) {
return;
}
$lines = file(static::PATH_ENV, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) {
throw new Exception('Unable to read environment file "' . static::PATH_ENV . '"');
}
foreach ($lines as $line) {
if (preg_match('/^\s*(?:(?<comment>#).+|(?<key>[a-zA-Z0-9_-]+)=(?<value>.+))$/i', $line, $match) !== 1) {
continue; // Ligne invalide
}
if (isset($match['comment']) && trim($match['comment']) !== '') {
continue; // Commentaire
}
$this->properties[mb_strtoupper($match['key'])] = $match['value'];
}
}
}

@ -1,4 +1,4 @@
WEBSITE_NAME=Foo
WEBSITE_NAME="Foo Bar"
DB_NAME=Bar
DB_LOGIN=Bar

Loading…
Cancel
Save