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

Csv   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 2
dl 0
loc 54
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getData() 0 17 3
A validateSyntax() 0 12 3
A getFields() 0 8 1
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