|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types = 1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Spreadsheet\Writer; |
|
5
|
|
|
|
|
6
|
|
|
use Spreadsheet\{ |
|
7
|
|
|
SpreadsheetInterface, |
|
8
|
|
|
Exception\InvalidArgumentException, |
|
9
|
|
|
SheetInterface, |
|
10
|
|
|
RowInterface, |
|
11
|
|
|
CellInterface, |
|
12
|
|
|
File\Csv |
|
13
|
|
|
}; |
|
14
|
|
|
use Innmind\Filesystem\{ |
|
15
|
|
|
FileInterface, |
|
16
|
|
|
Directory, |
|
17
|
|
|
Stream\Stream |
|
18
|
|
|
}; |
|
19
|
|
|
|
|
20
|
|
|
final class CsvWriter implements WriterInterface |
|
21
|
|
|
{ |
|
22
|
|
|
private $delimiter; |
|
23
|
|
|
private $withHeader; |
|
24
|
|
|
|
|
25
|
4 |
|
public function __construct(string $delimiter, bool $withHeader) |
|
26
|
|
|
{ |
|
27
|
4 |
|
if (empty($delimiter)) { |
|
28
|
|
|
throw new InvalidArgumentException; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
4 |
|
$this->delimiter = $delimiter; |
|
32
|
4 |
|
$this->withHeader = $withHeader; |
|
33
|
4 |
|
} |
|
34
|
|
|
|
|
35
|
3 |
|
public function write(SpreadsheetInterface $spreadsheet): FileInterface |
|
36
|
|
|
{ |
|
37
|
|
|
$directory = $spreadsheet |
|
38
|
3 |
|
->sheets() |
|
39
|
3 |
|
->reduce( |
|
40
|
3 |
|
new Directory($spreadsheet->name()), |
|
41
|
|
|
function(Directory $carry, string $name, SheetInterface $sheet): Directory { |
|
42
|
3 |
|
return $carry->add($this->buildFile($sheet)); |
|
43
|
3 |
|
} |
|
44
|
|
|
); |
|
45
|
|
|
|
|
46
|
3 |
|
if ($directory->count() === 1) { |
|
47
|
2 |
|
return $directory->get( |
|
48
|
2 |
|
$spreadsheet->sheets()->values()->first()->name().'.csv' |
|
49
|
|
|
); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
1 |
|
return $directory; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
3 |
|
private function buildFile(SheetInterface $sheet): FileInterface |
|
56
|
|
|
{ |
|
57
|
3 |
|
$csv = fopen('php://temp', 'r+'); |
|
58
|
|
|
|
|
59
|
3 |
|
if ($this->withHeader) { |
|
60
|
2 |
|
fputcsv($csv, $sheet->columns()->keys()->toPrimitive(), $this->delimiter); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
$sheet |
|
64
|
3 |
|
->rows() |
|
65
|
3 |
|
->reduce( |
|
66
|
|
|
$csv, |
|
67
|
|
|
function($carry, $identifier, RowInterface $row) { |
|
68
|
3 |
|
fputcsv( |
|
69
|
|
|
$carry, |
|
70
|
3 |
|
$row->cells()->reduce( |
|
71
|
3 |
|
[], |
|
72
|
3 |
|
function(array $carry, $column, CellInterface $cell): array { |
|
73
|
3 |
|
$carry[] = $cell->value(); |
|
74
|
|
|
|
|
75
|
3 |
|
return $carry; |
|
76
|
3 |
|
} |
|
77
|
|
|
), |
|
78
|
3 |
|
$this->delimiter |
|
79
|
|
|
); |
|
80
|
|
|
|
|
81
|
3 |
|
return $carry; |
|
82
|
3 |
|
} |
|
83
|
|
|
); |
|
84
|
|
|
|
|
85
|
3 |
|
return new Csv($sheet->name(), new Stream($csv)); |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|