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

Csv   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 2
dl 0
loc 54
ccs 23
cts 23
cp 1
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 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