Passed
Push — main ( af960c...f0a759 )
by Alberto
01:26
created

ReadCSVTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 54
rs 10
c 0
b 0
f 0
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A readCSVFile() 0 20 4
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * BEdita Brevia plugin
6
 *
7
 * Copyright 2023 Atlas Srl
8
 */
9
namespace Brevia\BEdita\Utility;
10
11
/**
12
 * Add CSV read methods.
13
 *
14
 * Tip: we could use https://github.com/bedita/import-tools/blob/main/src/Utility/CsvTrait.php instead
15
 */
16
trait ReadCSVTrait
17
{
18
    /**
19
     * CSV default options
20
     *
21
     * @var array
22
     */
23
    protected array $csvOptions = [
24
        'delimiter' => ',',
25
        'enclosure' => '"',
26
        'escape' => '\\',
27
    ];
28
29
    /**
30
     * CSV file keys read from header
31
     *
32
     * @var array
33
     */
34
    protected array $csvKeys = [];
35
36
    /**
37
     * CSV file data content organized as associative array with `key` => `value`
38
     *
39
     * @var array
40
     */
41
    protected array $csvData = [];
42
43
    /**
44
     * Read CSV file and populate `csvKeys` and `csvData` arrays
45
     *
46
     * @param string $filepath CSV file path
47
     * @param array $options CSV options overriding defaults
48
     * @return void
49
     */
50
    public function readCSVFile(string $filepath, ?array $options = []): void
51
    {
52
        $options = array_merge($this->csvOptions, (array)$options);
53
        $this->csvKeys = $this->csvData = [];
54
55
        $filecontent = file($filepath); // <= into an array
56
        if (empty($filecontent)) {
57
            return;
58
        }
59
        // read keys from first line
60
        $line = array_shift($filecontent);
61
        $this->csvKeys = str_getcsv($line, $options['delimiter'], $options['enclosure'], $options['escape']);
62
        $this->csvKeys = array_map('trim', $this->csvKeys);
63
        // read data using keys
64
        foreach ($filecontent as $line) {
65
            $values = str_getcsv($line, $options['delimiter'], $options['enclosure'], $options['escape']);
66
            if (count($values) != count($this->csvKeys)) {
67
                continue;
68
            }
69
            $this->csvData[] = array_combine($this->csvKeys, $values);
70
        }
71
    }
72
}
73