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\NotFoundException; |
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 readCsv($path): \Generator |
34
|
|
|
{ |
35
|
|
|
try { |
36
|
|
|
$fh = fopen($path, 'rb'); |
37
|
|
|
} catch (\Exception $e) { |
38
|
|
|
throw new NotFoundException(sprintf('File not found: %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
|
|
|
$i = 0; |
47
|
|
|
while (($row = fgetcsv($fh, null, $delimiter, $enclosure, $escape)) !== false) { |
48
|
|
|
yield array_combine($header, $row); |
49
|
|
|
$i++; |
50
|
|
|
} |
51
|
|
|
flock($fh, LOCK_UN); |
52
|
|
|
fclose($fh); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|