Completed
Push — development ( fe9d76...92122b )
by Thomas
05:41 queued 01:34
created

FileParser::getSanitizedFileContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace Oc\FieldNotes\Import;
4
5
use League\Csv\Reader;
6
use Oc\FieldNotes\Exception\FileFormatException;
7
use Symfony\Component\HttpFoundation\File\File;
8
9
/**
10
 * Dear brave soul
11
 * Once you are done trying to "optimize" this class,
12
 * and break everything but didn't recognize in first place,
13
 * please increment the following counter as a warning
14
 * for the next brave soul
15
 * total_hours_wasted = 42
16
 */
17
class FileParser
18
{
19
    /**
20
     * @var StructMapper
21
     */
22
    private $structMapper;
23
24
    public function __construct(StructMapper $structMapper)
25
    {
26
        $this->structMapper = $structMapper;
27
    }
28
29
    /**
30
     * @throws FileFormatException
31
     */
32
    public function parseFile(File $file): array
33
    {
34
        $csv = Reader::createFromPath($file->getRealPath());
35
        $csv->setDelimiter(',');
36
        $csv->setEnclosure('"');
37
38
        $rows = $this->getRowsFromCsv($csv);
39
40
        return $this->structMapper->map($rows);
41
    }
42
43
    private function getRowsFromCsv(Reader $csv): array
44
    {
45
        $lines = [];
46
        $rows = [];
47
        $content = $csv->getContent();
48
        $content = mb_convert_encoding($content, 'UTF-8', 'UTF-16LE');
49
50
        $rawLines = array_filter(explode("\n", $content));
51
        $tmpString = '';
52
        // is used to support line breaks in the comment section
53
        foreach ($rawLines as $key => $rawLine) {
54
            $columnCheck = count(str_getcsv($rawLines[$key + 1]));
55
            $tmpString .= $rawLine;
56
            if ($columnCheck === 4 || $rawLines[$key + 1] === null) {
57
                $lines[] = $tmpString;
58
                $tmpString = '';
59
            }
60
        }
61
62
        foreach ($lines as $line) {
63
            $row = str_getcsv($line, ',', '"');
64
            $row = array_map('trim', $row);
65
66
            if (count($row) < 4) {
67
                throw new FileFormatException('A row contains more or less than 4 columns');
68
            }
69
70
            $rows[] = $row;
71
        }
72
73
        return $rows;
74
    }
75
}
76