EnvConfig: use TExternalFile instead of a constant for config file path

2.x
Julien Rosset 3 years ago
parent 97ba16a962
commit 65ce5e2382

@ -10,19 +10,4 @@ composer require jrosset/envreader
## Usage ## Usage
```php Check "tests" directory for various examples
<?php
use jrosset\EnvReader\EnvConfig;
class Env extends EnvConfig {
protected const PATH_ENV = __DIR__ . '/.env';
protected function initProperties (): array {
return [
'WEBSITE_MODE' => 'DEV',
'WEBSITE_NAME' => 'Generic site'
];
}
}
```

@ -4,23 +4,21 @@ namespace jrosset\EnvReader;
use Exception; use Exception;
class EnvConfig extends GenericConfig { abstract class EnvConfig extends GenericConfig {
/** use TExternalFile;
* ENV file path
*/
protected const PATH_ENV = '.env';
/** /**
* @inheritDoc * @inheritDoc
*/ */
protected function readConfig (): void { protected function readConfig (): void {
if (!file_exists(static::PATH_ENV)) { $configFile = $this->getConfigFilePath();
if (!file_exists($configFile)) {
return; return;
} }
$lines = file(static::PATH_ENV, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); $lines = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) { if ($lines === false) {
throw new Exception('Unable to read environment file "' . static::PATH_ENV . '"'); throw new Exception('Unable to read environment file "' . $configFile . '"');
} }
foreach ($lines as $line) { foreach ($lines as $line) {

@ -6,17 +6,15 @@ require_once __DIR__ . '/../vendor/autoload.php';
use jrosset\EnvReader\EnvConfig; use jrosset\EnvReader\EnvConfig;
class Env extends EnvConfig { class Env extends EnvConfig {
/**
* @inheritdoc
*/
protected const PATH_ENV = __DIR__ . '/.env';
protected function initialProperties (): array { protected function initialProperties (): array {
return [ return [
'WEBSITE_MODE' => 'DEV', 'WEBSITE_MODE' => 'DEV',
'WEBSITE_NAME' => 'Generic site', 'WEBSITE_NAME' => 'Generic site',
]; ];
} }
protected function getConfigFilePath (): string {
return __DIR__ . '/.env';
}
} }
var_dump(Env::getInstance()->getProperties()); var_dump(Env::getInstance()->getProperties());

Loading…
Cancel
Save