Completed
Push — master ( 64470f...3a69fd )
by Florian
02:24
created

CsvParser::parse()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 21
ccs 0
cts 20
cp 0
rs 9.0534
cc 4
eloc 15
nc 2
nop 2
crap 20
1
<?php
2
3
namespace Laposte\DatanovaBundle\Parser;
4
5
use Laposte\DatanovaBundle\Service\Finder;
6
7
class CsvParser implements ParserInterface
8
{
9
    /** File format */
10
    const FORMAT = 'csv';
11
12
    /** CSV delimiter */
13
    const DELIMITER = ';';
14
15
    /**
16
     * @var Finder
17
     */
18
    private $finder;
19
20
    /**
21
     * @param Finder $finder
22
     */
23
    public function __construct(Finder $finder)
24
    {
25
        $this->finder = $finder;
26
    }
27
28
    /**
29
     * @param string $dataset
30
     * @param string $delimiter
31
     *
32
     * @return false|array
33
     */
34
    public function parse($dataset, $delimiter = self::DELIMITER)
35
    {
36
        $data = false;
37
        $path = $this->finder->findDataset($dataset, self::FORMAT);
38
        if (false !== $path) {
39
            $data = array();
40
            $lines = file($path);
41
            $columns = str_getcsv($lines[0], $delimiter);
42
            unset($lines[0]);
43
            foreach ($lines as $line) {
44
                $lineValues = str_getcsv($line, $delimiter);
45
                $lineData = array();
46
                foreach ($lineValues as $key => $value) {
47
                    $lineData[$columns[$key]] = $value;
48
                }
49
                $data[] = $lineData;
50
            }
51
        }
52
53
        return $data;
54
    }
55
}
56