Completed
Pull Request — master (#6)
by
unknown
02:44
created

Csv::getData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 0
crap 12
1
<?php
2
3
namespace Dyrynda\Artisan\BulkImport\Handlers;
4
5
use SplFileObject;
6
use Dyrynda\Artisan\Exceptions\ImportFileException;
7
use Dyrynda\Artisan\BulkImport\BulkImportFileHandler;
8
9
class Csv extends Base implements BulkImportFileHandler
10
{
11 1
    public function __construct($file)
12
    {
13 1
        parent::__construct($file);
14
15
        $this->fileHandle->setFlags(SplFileObject::READ_CSV);
16
    }
17
18
    public function getData()
19
    {
20
        $this->fileHandle->rewind();
21
22
        $data = [];
23
24
        $fields = $this->getFields();
25
26
        foreach ($this->fileHandle as $index => $row) {
27
            // skip header
28
            if ($index != 0) {
29
                $data[] = array_combine($fields, $row);
30
            }
31
        }
32
33
        return $data;
34
    }
35
36
    protected function validateSyntax()
37
    {
38
        $this->fileHandle->rewind();
39
40
        $fields = array_filter(array_map('trim', explode(',', $this->fileHandle->current())));
41
42
        foreach ($this->fileHandle as $row) {
43
            if (count($fields) != count(explode(',', $row))) {
44
                throw ImportFileException::invalidSyntax($this->file->getFilename());
45
            }
46
        }
47
    }
48
49
    /**
50
     * Get list of columns from the file.
51
     *
52
     * @return array
53
     */
54
    protected function getFields()
55
    {
56
        $this->fileHandle->rewind();
57
58
        $fields = array_filter(array_map('strtolower', array_map('trim', $this->fileHandle->current())));
59
60
        return $fields;
61
    }
62
}
63