1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Lib\Env\Parser; |
4
|
|
|
|
5
|
|
|
use Lib\Env\Exception\FormatException; |
6
|
|
|
|
7
|
|
|
class DotenvParser implements EnvParserInterface |
8
|
|
|
{ |
9
|
|
|
private const REGEX_VARNAME = '(export[ \t]++)?((?i:[A-Z][A-Z0-9_]*+))'; |
10
|
|
|
private const REGEX_QUOTED = '/["\']+(?:.*)["\']+$/A'; |
11
|
|
|
private const REGEX_EMPTY_OR_COMMENT = '(?:\s*+(?:#[^\n]*+)?+)++'; |
12
|
|
|
|
13
|
|
|
public function parse(string $data): array |
14
|
|
|
{ |
15
|
|
|
$values = []; |
16
|
|
|
$lines = explode("\n", $data); |
17
|
|
|
foreach ($lines as $line) { |
18
|
|
|
if ($this->emptyLine($line)) { |
19
|
|
|
continue; |
20
|
|
|
} |
21
|
|
|
[$name, $value] = explode('=', $line, 2); |
22
|
|
|
try { |
23
|
|
|
$this->lexName($name); |
24
|
|
|
$this->lexValue($value); |
25
|
|
|
} catch (\Exception $e) { |
26
|
|
|
throw $e; |
27
|
|
|
} |
28
|
|
|
$values[$name] = $value; |
29
|
|
|
} |
30
|
|
|
return $values; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
private function emptyLine(string $line): bool |
34
|
|
|
{ |
35
|
|
|
if (preg_match('/'.self::REGEX_EMPTY_OR_COMMENT.'/A', $line)) { |
36
|
|
|
return true; |
37
|
|
|
} |
38
|
|
|
return false; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
private function lexName(string $name): string |
42
|
|
|
{ |
43
|
|
|
if (!preg_match(self::REGEX_VARNAME, $name, $matches)) { |
44
|
|
|
throw new FormatException('name', $name); |
45
|
|
|
} |
46
|
|
|
return $matches[2]; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function lexValue(string $value): string |
50
|
|
|
{ |
51
|
|
|
// strip inline comments on the right hand side |
52
|
|
|
$value = explode(' #', $value, 2)[0]; |
53
|
|
|
|
54
|
|
|
if ($this->isQuoted($value)) { |
55
|
|
|
// strip quotes |
56
|
|
|
$value = substr(substr($value, 0, -1), 1); |
57
|
|
|
|
58
|
|
|
$pos = strpos($value, '"'); |
59
|
|
|
if (0 !== $pos && \strlen($value) - 1 !== $pos) { |
60
|
|
|
if ($value{$pos - 1} !== '\\') { |
61
|
|
|
throw new FormatException('value', $value); |
62
|
|
|
} |
|
|
|
|
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
private function isQuoted(string $value): bool |
68
|
|
|
{ |
69
|
|
|
return (bool) preg_match(self::REGEX_QUOTED, $value); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|
For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example: