AbstractBase::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 4
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace EasyCSV;
6
7
use SplFileObject;
8
use const PHP_EOL;
9
use function file_exists;
10
use function implode;
11
use function strlen;
12
use function touch;
13
14
abstract class AbstractBase
15
{
16
    /** @var string */
17
    protected $path;
18
19
    /** @var string */
20
    protected $mode;
21
22
    /** @var bool */
23
    protected $isNeedBOM = false;
24
25
    /** @var string[] */
26
    protected $initialHeaders = [];
27
28
    /** @var SplFileObject|null */
29
    protected $handle;
30
31
    /** @var string */
32
    protected $delimiter = ',';
33
34
    /** @var string */
35
    protected $enclosure = '"';
36
37
    /**
38
     * @param string[] $initialHeaders
39
     */
40 7
    public function __construct(
41
        string $path,
42
        string $mode = 'r+',
43
        bool $isNeedBOM = false,
44
        array $initialHeaders = []
45
    ) {
46 7
        $this->path           = $path;
47 7
        $this->mode           = $mode;
48 7
        $this->isNeedBOM      = $isNeedBOM;
49 7
        $this->initialHeaders = $initialHeaders;
50 7
        $this->handle         = $this->initializeHandle();
51 7
    }
52
53 5
    public function __destruct()
54
    {
55 5
        $this->handle = null;
56 5
    }
57
58
    public function setDelimiter(string $delimiter) : void
59
    {
60
        $this->delimiter = $delimiter;
61
    }
62
63
    public function setEnclosure(string $enclosure) : void
64
    {
65
        $this->enclosure = $enclosure;
66
    }
67
68 37
    protected function getHandle() : SplFileObject
69
    {
70 37
        if ($this->handle === null) {
71
            $this->handle = $this->initializeHandle();
72
        }
73
74 37
        return $this->handle;
75
    }
76
77 7
    private function initializeHandle() : SplFileObject
78
    {
79 7
        $isNewFile = false;
80
81 7
        if (! file_exists($this->path)) {
82
            touch($this->path);
83
84
            $isNewFile = true;
85
        }
86
87 7
        $handle = new SplFileObject($this->path, $this->mode);
88 7
        $handle->setFlags(SplFileObject::DROP_NEW_LINE);
89
90 7
        if ($this->isNeedBOM) {
91 7
            $handle->fwrite("\xEF\xBB\xBF");
92
        }
93
94 7
        if ($isNewFile && $this->initialHeaders !== []) {
95
            $headerLine = implode(',', $this->initialHeaders) . PHP_EOL;
96
97
            $handle->fwrite($headerLine, strlen($headerLine));
98
        }
99
100 7
        return $handle;
101
    }
102
}
103