22
33namespace DevCoder ;
44
5+ use DevCoder \Processor \AbstractProcessor ;
6+ use DevCoder \Processor \BooleanProcessor ;
7+ use DevCoder \Processor \QuotedProcessor ;
8+
59class DotEnv
610{
7- /**
8- * Convert true and false to booleans, instead of:
9- *
10- * VARIABLE=false -> ['VARIABLE' => 'false']
11- *
12- * it will be
13- *
14- * VARIABLE=false -> ['VARIABLE' => false]
15- *
16- * default = true
17- */
18- const PROCESS_BOOLEANS = 'PROCESS_BOOLEANS ' ;
19-
2011 /**
2112 * The directory where the .env file can be located.
2213 *
@@ -27,26 +18,42 @@ class DotEnv
2718 /**
2819 * Configure the options on which the parsed will act
2920 *
30- * @var array
21+ * @var string[]
3122 */
32- protected $ options = [];
23+ protected $ processors = [];
3324
34- public function __construct (string $ path , array $ options = [] )
25+ public function __construct (string $ path , array $ processors = null )
3526 {
3627 if (!file_exists ($ path )) {
3728 throw new \InvalidArgumentException (sprintf ('%s does not exist ' , $ path ));
3829 }
3930
4031 $ this ->path = $ path ;
4132
42- $ this ->processOptions ( $ options );
33+ $ this ->setProcessors ( $ processors );
4334 }
4435
45- private function processOptions (array $ options ) : void
36+ private function setProcessors (array $ processors = null ) : DotEnv
4637 {
47- $ this ->options = array_merge ([
48- static ::PROCESS_BOOLEANS => true
49- ], $ options );
38+ /**
39+ * Fill with default processors
40+ */
41+ if ($ processors === null ) {
42+ $ this ->processors = [
43+ BooleanProcessor::class,
44+ QuotedProcessor::class
45+ ];
46+
47+ return $ this ;
48+ }
49+
50+ foreach ($ processors as $ processor ) {
51+ if (is_subclass_of ($ processor , AbstractProcessor::class)) {
52+ $ this ->processors [] = $ processor ;
53+ }
54+ }
55+
56+ return $ this ;
5057 }
5158
5259 /**
@@ -78,19 +85,31 @@ public function load() : void
7885 }
7986 }
8087
81- private function processValue (string $ value ) {
88+ /**
89+ * Process the value with the configured processors
90+ *
91+ * @param string $value The value to process
92+ * @return string|bool
93+ */
94+ private function processValue (string $ value )
95+ {
96+ /**
97+ * First trim spaces and quotes if configured
98+ */
8299 $ trimmedValue = trim ($ value );
83100
84- if (!empty ($ this ->options [static ::PROCESS_BOOLEANS ])) {
85- $ loweredValue = strtolower ($ trimmedValue );
86-
87- $ isBoolean = in_array ($ loweredValue , ['true ' , 'false ' ], true );
101+ foreach ($ this ->processors as $ processor ) {
102+ /** @var AbstractProcessor $processorInstance */
103+ $ processorInstance = new $ processor ($ trimmedValue );
88104
89- if ($ isBoolean ) {
90- return $ loweredValue === ' true ' ;
105+ if ($ processorInstance -> canBeProcessed () ) {
106+ return $ processorInstance -> execute () ;
91107 }
92108 }
93109
110+ /**
111+ * Does not match any processor options, return as is
112+ */
94113 return $ trimmedValue ;
95114 }
96115}
0 commit comments