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

Csv::getData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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