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

Csv::validateSyntax()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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