Add EnvConfig
parent
0cc6aee547
commit
5335c41548
@ -1,28 +1,28 @@
|
|||||||
# PhpEnvReader
|
# PhpEnvReader
|
||||||
|
|
||||||
__Utility class for ENV file reading__
|
__Utility class for ENV file reading__
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```
|
```
|
||||||
composer require jrosset/envreader
|
composer require jrosset/envreader
|
||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```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 {
|
||||||
return [
|
return [
|
||||||
'WEBSITE_MODE' => 'DEV',
|
'WEBSITE_MODE' => 'DEV',
|
||||||
'WEBSITE_NAME' => 'Generic site'
|
'WEBSITE_NAME' => 'Generic site'
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
@ -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']);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue