ReadCSVTrait::readCSVFile()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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