Passed
Pull Request — master (#1)
by Flavien
06:34 queued 03:23
created

ConvertCsvToArray   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 63
ccs 0
cts 17
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A convert() 0 14 3
A fillData() 0 10 2
A getFileHandle() 0 8 3
1
<?php
2
3
namespace QualityCode\TransformAndLoadBundle\Services;
4
5
class ConvertCsvToArray
6
{
7
    /**
8
     * @var array
9
     */
10
    private $header = null;
11
12
    /**
13
     * @var array
14
     */
15
    private $data = array();
16
17
    /**
18
     * @param string $fileName
19
     * @param string $delimiter
20
     *
21
     * @return array
22
     */
23
    public function convert(string $fileName, $delimiter = ',')
24
    {
25
        $handle = $this->getFileHandle($fileName);
26
        if ($handle === false) {
27
            return array();
28
        }
29
30
        while (($row = fgetcsv($handle, 0, $delimiter)) !== false) {
31
            $this->fillData($row);
32
        }
33
        fclose($handle);
34
35
        return $this->data;
36
    }
37
38
    /**
39
     * @param array $row
40
     *
41
     * @return ConvertCsvToArray
42
     */
43
    protected function fillData(array $row)
44
    {
45
        if (empty($this->header)) {
46
            $this->header = $row;
47
        } else {
48
            $this->data[] = array_combine($this->header, $row);
49
        }
50
51
        return $this;
52
    }
53
54
    /**
55
     * @param string $fileName
56
     *
57
     * @return bool|resource
58
     */
59
    private function getFileHandle(string $fileName)
60
    {
61
        if (!file_exists($fileName) || !is_readable($fileName)) {
62
            return false;
63
        }
64
65
        return fopen($fileName, 'r');
66
    }
67
}
68