Add EnvConfig

2.x
Julien Rosset 3 years ago
parent 0cc6aee547
commit 5335c41548

@ -13,9 +13,9 @@ composer require jrosset/envreader
```php ```php
<?php <?php
use jrosset\EnvReader\BaseEnv; use jrosset\EnvReader\EnvConfig;
class Env extends BaseEnv { class Env extends EnvConfig {
protected const PATH_ENV = __DIR__ . '/.env'; protected const PATH_ENV = __DIR__ . '/.env';
protected function initProperties (): array { protected function initProperties (): array {

@ -0,0 +1,50 @@
<?php
namespace jrosset\EnvReader;
use Exception;
class EnvConfig extends GenericConfig {
/**
* ENV file path
*/
protected const PATH_ENV = '.env';
/**
* @inheritDoc
*/
protected function readConfig (): 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-Z\\d_-]+)=(?<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->set($match['key'], $match['value']);
}
}
}

@ -3,15 +3,15 @@
require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../vendor/autoload.php';
use jrosset\EnvReader\BaseEnv; use jrosset\EnvReader\EnvConfig;
class Env extends BaseEnv { class Env extends EnvConfig {
/** /**
* @inheritdoc * @inheritdoc
*/ */
protected const PATH_ENV = __DIR__ . '/.env'; protected const PATH_ENV = __DIR__ . '/.env';
protected function initProperties (): array { protected function initialProperties (): array {
return [ return [
'WEBSITE_MODE' => 'DEV', 'WEBSITE_MODE' => 'DEV',
'WEBSITE_NAME' => 'Generic site', 'WEBSITE_NAME' => 'Generic site',
Loading…
Cancel
Save