Passed
Pull Request — master (#84)
by Dante
10:52
created

CsvTrait::read()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 17
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 22
rs 9.7
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
18
use Cake\Core\InstanceConfigTrait;
19
use Cake\Http\Exception\BadRequestException;
20
use Symfony\Component\Filesystem\Exception\FileNotFoundException;
0 ignored issues
show
Bug introduced by
The type Symfony\Component\Filesy...n\FileNotFoundException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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