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

Json::validateSyntax()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 16
c 0
b 0
f 0
ccs 0
cts 13
cp 0
rs 8.8571
cc 5
eloc 8
nc 4
nop 0
crap 30
1
<?php
2
3
namespace Dyrynda\Artisan\BulkImport\Handlers;
4
5
use Dyrynda\Artisan\Exceptions\ImportFileException;
6
use Dyrynda\Artisan\BulkImport\BulkImportFileHandler;
7
8
class Json extends Base implements BulkImportFileHandler
9
{
10
    public function getData()
11
    {
12
        return json_decode(file_get_contents($this->filePath), true, 512, JSON_BIGINT_AS_STRING);
13
    }
14
15
    protected function validateSyntax()
16
    {
17
        $data = json_decode(file_get_contents($this->filePath), true);
18
19
        if (json_last_error()) {
20
            throw ImportFileException::invalidSyntax($this->file->getFilename());
21
        }
22
        
23
        $fields = array_keys($data[0]);
24
25
        foreach ($data as $row) {
26
           if (count($fields) != count($row) || count(array_intersect($fields, array_keys($row))) != count($fields)) {
27
                throw ImportFileException::invalidSyntax($this->file->getFilename(), 'Fields not consistent');
28
           }
29
        }
30
    }
31
    
32
    /**
33
     * Get list of columns from the file
34
     *
35
     * @return array
36
     */
37
    protected function getFields()
38
    {
39
        $data = json_decode(file_get_contents($this->filePath), true);
40
41
        return isset($data[0]) ? array_map('strtolower', array_map('trim', array_keys($data[0]))) : [];
42
    }    
43
}
44