edmondscommerce /
doctrine-static-meta
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace EdmondsCommerce\DoctrineStaticMeta; |
||
| 6 | |||
| 7 | use EdmondsCommerce\DoctrineStaticMeta\Exception\ConfigException; |
||
| 8 | |||
| 9 | /** |
||
| 10 | * Class SimpleEnv |
||
| 11 | * |
||
| 12 | * A simplistic take on reading .env files |
||
| 13 | * |
||
| 14 | * We only require parsing very simple key=value pairs |
||
| 15 | * |
||
| 16 | * For a more fully featured library, see https://github.com/vlucas/phpdotenv |
||
| 17 | * |
||
| 18 | * @package EdmondsCommerce\DoctrineStaticMeta |
||
| 19 | * @SuppressWarnings(PHPMD.Superglobals) |
||
| 20 | */ |
||
| 21 | class SimpleEnv |
||
| 22 | { |
||
| 23 | 10 | public static function setEnv(string $filePath, array &$server = null): void |
|
| 24 | { |
||
| 25 | 10 | if (null === $server) { |
|
| 26 | $server =& $_SERVER; |
||
| 27 | } |
||
| 28 | 10 | if (!file_exists($filePath)) { |
|
| 29 | throw new ConfigException('Env file path ' . $filePath . ' does not exist'); |
||
| 30 | } |
||
| 31 | 10 | $lines = file($filePath); |
|
| 32 | 10 | foreach ($lines as $line) { |
|
| 33 | 10 | self::processLine($line, $server); |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 34 | } |
||
| 35 | 10 | } |
|
| 36 | |||
| 37 | 10 | private static function processLine(string $line, array &$server): void |
|
| 38 | { |
||
| 39 | #skip comments |
||
| 40 | 10 | if (preg_match('%^\s*#%', $line)) { |
|
| 41 | 2 | return; |
|
| 42 | } |
||
| 43 | 10 | preg_match( |
|
| 44 | #strip leading spaces |
||
| 45 | '%^[[:space:]]*' |
||
| 46 | #strip leading `export` |
||
| 47 | . '(?:export[[:space:]]+|)' |
||
| 48 | #parse out the key and assign to named match |
||
| 49 | . '(?<key>[^=]+?)' |
||
| 50 | #strip out `=`, possibly with space around it |
||
| 51 | . '[[:space:]]*=[[:space:]]*' |
||
| 52 | #strip out possible quotes |
||
| 53 | . "(?:\"|'|)" |
||
| 54 | #parse out the value and assign to named match |
||
| 55 | . "(?<value>[^\"']+?)" |
||
| 56 | #strip out possible quotes |
||
| 57 | . "(?:\"|'|)" |
||
| 58 | #string out trailing space to end of line |
||
| 59 | 10 | . '[[:space:]]*$%', |
|
| 60 | 10 | $line, |
|
| 61 | 10 | $matches |
|
| 62 | ); |
||
| 63 | 10 | if (5 !== count($matches)) { |
|
| 64 | 2 | return; |
|
| 65 | } |
||
| 66 | 10 | list(, $key, $value) = $matches; |
|
| 67 | 10 | if (!isset($server[$key])) { |
|
| 68 | 10 | $server[$key] = $value; |
|
| 69 | } |
||
| 70 | 10 | } |
|
| 71 | } |
||
| 72 |