1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Rfussien\Dotenv; |
4
|
|
|
|
5
|
|
|
class Parser |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* parsed content of the dotenv file |
9
|
|
|
*/ |
10
|
|
|
private $content = []; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Which parsing style is used |
14
|
|
|
* |
15
|
|
|
* @see http://php.net/parse_ini_file |
16
|
|
|
*/ |
17
|
|
|
private $scannerMode; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Set the default parsing style |
21
|
|
|
*/ |
22
|
39 |
|
public function __construct() |
23
|
|
|
{ |
24
|
|
|
/** |
25
|
|
|
* INI_SCANNER_TYPED won't work on hhvm |
26
|
|
|
* @see https://github.com/facebook/hhvm/issues/5239 |
27
|
|
|
*/ |
28
|
39 |
|
if (defined('HHVM_VERSION')) { |
29
|
|
|
$this->setScannerMode(\INI_SCANNER_NORMAL); |
30
|
|
|
} else { |
31
|
39 |
|
$this->setScannerMode(\INI_SCANNER_TYPED); |
32
|
|
|
} |
33
|
39 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Set the scanner_mode used by the parse_ini_file function |
37
|
|
|
*/ |
38
|
39 |
|
public function setScannerMode($scannerMode) |
39
|
|
|
{ |
40
|
39 |
|
$this->scannerMode = $scannerMode; |
41
|
39 |
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* parse the .env file |
45
|
|
|
* |
46
|
|
|
* @param string $file file to parse |
47
|
|
|
* |
48
|
|
|
* @return string Returns the phrase passed in |
49
|
|
|
*/ |
50
|
39 |
|
public function parse($file) |
51
|
|
|
{ |
52
|
|
|
try { |
53
|
39 |
|
$this->content = parse_ini_string( |
54
|
26 |
|
file_get_contents($file), |
55
|
39 |
|
false, |
56
|
39 |
|
$this->scannerMode |
57
|
26 |
|
); |
58
|
28 |
|
} catch (\Exception $e) { |
59
|
6 |
|
throw new Exception\ParseException($e); |
60
|
|
|
} |
61
|
|
|
|
62
|
33 |
|
return $this; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Transforme the boolean used as string in the env file to real boolean |
67
|
|
|
*/ |
68
|
|
|
public function sanitizeValues() |
69
|
|
|
{ |
70
|
3 |
|
array_walk($this->content, function (&$value) { |
71
|
|
|
// sanitize boolean values |
72
|
3 |
|
if (in_array($value, ['true', 'on', 'yes', 'false', 'off', 'no'])) { |
73
|
3 |
|
$value = filter_var($value, FILTER_VALIDATE_BOOLEAN); |
74
|
2 |
|
} |
75
|
3 |
|
}); |
76
|
|
|
|
77
|
3 |
|
return $this; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Return the parsed content |
82
|
|
|
* |
83
|
|
|
* @return array content |
84
|
|
|
*/ |
85
|
33 |
|
public function getContent() |
86
|
|
|
{ |
87
|
33 |
|
return $this->content; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|