Passed
Pull Request — master (#84)
by Dante
01:50
created

CsvTrait   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 29
rs 10
wmc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A read() 0 19 3
1
<?php
2
declare(strict_types=1);
3
4
/**
5
 * BEdita, API-first content management framework
6
 * Copyright 2023 Atlas Srl, Chialab Srl
7
 *
8
 * This file is part of BEdita: you can redistribute it and/or modify
9
 * it under the terms of the GNU Lesser General Public License as published
10
 * by the Free Software Foundation, either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
14
 */
15
namespace BEdita\WebTools\Utility;
16
17
use Cake\Core\InstanceConfigTrait;
18
use Cake\Http\Exception\BadRequestException;
19
20
/**
21
 * Trait for share Csv stuff.
22
 */
23
trait CsvTrait
24
{
25
    use InstanceConfigTrait;
26
27
    /**
28
     * Progressively read a CSV file, line by line.
29
     *
30
     * @param string $path Path to CSV file.
31
     * @return \Generator<array<string, string>>
32
     */
33
    public function read($path): \Generator
34
    {
35
        $fh = fopen($path, 'rb');
36
        $options = $this->getConfig('csv');
37
        $delimiter = $options['delimiter'];
38
        $enclosure = $options['enclosure'];
39
        $escape = $options['escape'];
40
        flock($fh, LOCK_SH);
41
        $header = fgetcsv($fh, null, $delimiter, $enclosure, $escape);
42
        if ($header === false) {
43
            throw new BadRequestException(sprintf('Unable to get csv data for file: %s', $path));
44
        }
45
        $i = 0;
46
        while (($row = fgetcsv($fh, null, $delimiter, $enclosure, $escape)) !== false) {
47
            yield array_combine($header, $row);
48
            $i++;
49
        }
50
        flock($fh, LOCK_UN);
51
        fclose($fh);
52
    }
53
}
54