|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace sixlive\DotenvEditor; |
|
4
|
|
|
|
|
5
|
|
|
use Exception; |
|
6
|
|
|
use SplFileObject; |
|
7
|
|
|
use sixlive\DotenvEditor\Support\Arr; |
|
8
|
|
|
|
|
9
|
|
|
class EnvFile |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* @var \SplFileObject|null |
|
13
|
|
|
*/ |
|
14
|
|
|
protected $file; |
|
15
|
|
|
|
|
16
|
8 |
|
public function __construct($path) |
|
17
|
|
|
{ |
|
18
|
8 |
|
$this->file = new SplFileObject($path, 'r+'); |
|
19
|
8 |
|
} |
|
20
|
|
|
|
|
21
|
6 |
|
public function write($content) |
|
22
|
|
|
{ |
|
23
|
6 |
|
$this->file->fwrite($content); |
|
24
|
|
|
|
|
25
|
6 |
|
return $this; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
8 |
|
public function isEmpty() |
|
29
|
|
|
{ |
|
30
|
8 |
|
return $this->file->getSize() > 0; |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
3 |
|
public function toArray() |
|
34
|
|
|
{ |
|
35
|
3 |
|
return Arr::flatten($this->mapLineValuesAndKeys()); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function __call($name, $args = []) |
|
39
|
|
|
{ |
|
40
|
|
|
if (! method_exists($this, $name) && ! method_exists($this->file, $name)) { |
|
41
|
|
|
throw new Exception(sprintf('%s does not have a method %s', __CLASS__, $name)); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
return call_user_func_array( |
|
45
|
|
|
[method_exists($this, $name) ? $this : $this->file, $name], |
|
46
|
|
|
$args |
|
47
|
|
|
); |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
8 |
|
public function __destruct() |
|
51
|
|
|
{ |
|
52
|
8 |
|
$this->file = null; |
|
53
|
8 |
|
} |
|
54
|
|
|
|
|
55
|
|
|
private function configLines() |
|
56
|
|
|
{ |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
3 |
|
private function linesFromFile() |
|
60
|
|
|
{ |
|
61
|
3 |
|
return explode( |
|
62
|
3 |
|
"\n", |
|
63
|
3 |
|
$this->file->fread($this->file->getSize()) |
|
64
|
|
|
); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
private function convertLineValuesToArray() |
|
68
|
|
|
{ |
|
69
|
3 |
|
return array_map(function ($line) { |
|
70
|
3 |
|
return explode('=', $line); |
|
71
|
3 |
|
}, $this->linesFromFile()); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
private function mapLineValuesAndKeys() |
|
75
|
|
|
{ |
|
76
|
3 |
|
return array_map(function ($line) { |
|
77
|
3 |
|
if (count($line) === 2) { |
|
78
|
3 |
|
return [$line[0] => $line[1]]; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
3 |
|
return $line[0]; |
|
82
|
3 |
|
}, $this->convertLineValuesToArray()); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|