Completed
Pull Request — master (#6)
by
unknown
06:12 queued 29s
created

Csv::getFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

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