Completed
Push — master ( 2923a6...86d06a )
by TJ
02:57
created

EnvFile::isEmpty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
crap 1
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