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

EnvFile   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 75.76%

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 1
dl 0
loc 76
ccs 25
cts 33
cp 0.7576
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A write() 0 6 1
A isEmpty() 0 4 1
A toArray() 0 4 1
A __call() 0 11 4
A __destruct() 0 4 1
A configLines() 0 3 1
A linesFromFile() 0 7 1
A convertLineValuesToArray() 0 6 1
A mapLineValuesAndKeys() 0 10 2
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