Passed
Pull Request — master (#84)
by Dante
03:56 queued 01:59
created

CsvTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 32
rs 10
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A read() 0 22 4
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
use Cake\Http\Exception\NotFoundException;
20
21
/**
22
 * Trait for share Csv stuff.
23
 */
24
trait CsvTrait
25
{
26
    use InstanceConfigTrait;
27
28
    /**
29
     * Progressively read a CSV file, line by line.
30
     *
31
     * @param string $path Path to CSV file.
32
     * @return \Generator<array<string, string>>
33
     */
34
    public function read($path): \Generator
35
    {
36
        $fh = fopen($path, 'rb');
37
        if (!$fh) {
0 ignored issues
show
introduced by
$fh is of type resource, thus it always evaluated to false.
Loading history...
38
            throw new NotFoundException(sprintf('Unable to open file in read mode: %s', $path));
39
        }
40
        $options = $this->getConfig('csv');
41
        $delimiter = $options['delimiter'];
42
        $enclosure = $options['enclosure'];
43
        $escape = $options['escape'];
44
        flock($fh, LOCK_SH);
45
        $header = fgetcsv($fh, null, $delimiter, $enclosure, $escape);
46
        if ($header === false) {
47
            throw new BadRequestException(sprintf('Unable to get csv data for file: %s', $path));
48
        }
49
        $i = 0;
50
        while (($row = fgetcsv($fh, null, $delimiter, $enclosure, $escape)) !== false) {
51
            yield array_combine($header, $row);
52
            $i++;
53
        }
54
        flock($fh, LOCK_UN);
55
        fclose($fh);
56
    }
57
}
58