|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace WebServCo\Framework\Files; |
|
6
|
|
|
|
|
7
|
|
|
use WebServCo\Framework\Exceptions\FileException; |
|
8
|
|
|
|
|
9
|
|
|
final class CsvCreator |
|
10
|
|
|
{ |
|
11
|
|
|
protected string $delimiter; |
|
12
|
|
|
protected string $enclosure; |
|
13
|
|
|
|
|
14
|
|
|
public function __construct(string $delimiter = ',', string $enclosure = '"') |
|
15
|
|
|
{ |
|
16
|
|
|
$this->delimiter = $delimiter; |
|
17
|
|
|
$this->enclosure = $enclosure; |
|
18
|
|
|
} |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @param array<int,array<mixed>> $data |
|
22
|
|
|
*/ |
|
23
|
|
|
public function getCsvFile(string $fileName, array $data, bool $addHeader = true): CsvFile |
|
24
|
|
|
{ |
|
25
|
|
|
$csvData = $this->getCsvData($data, $addHeader); |
|
26
|
|
|
return new CsvFile($fileName, $csvData); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @param array<int,array<mixed>> $data |
|
31
|
|
|
*/ |
|
32
|
|
|
public function getCsvData(array $data, bool $addHeader = true): string |
|
33
|
|
|
{ |
|
34
|
|
|
if (!$data) { |
|
|
|
|
|
|
35
|
|
|
return ''; |
|
36
|
|
|
} |
|
37
|
|
|
try { |
|
38
|
|
|
// temporary file/memory wrapper; if bigger than 5MB will be written to temp file. |
|
39
|
|
|
$handle = \fopen('php://temp/maxmemory:' . (5 * 1024 * 1024), 'r+'); |
|
40
|
|
|
|
|
41
|
|
|
if (!\is_resource($handle)) { |
|
42
|
|
|
throw new FileException('Not a valid resource.'); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
// Add Byte Order mark (BOM) for UTF-8. |
|
46
|
|
|
\fwrite($handle, \chr(0xEF) . \chr(0xBB) . \chr(0xBF)); |
|
47
|
|
|
|
|
48
|
|
|
if ($addHeader) { |
|
49
|
|
|
$headerData = \current($data); |
|
50
|
|
|
if (false !== $headerData) { |
|
51
|
|
|
\fputcsv($handle, \array_keys($headerData), $this->delimiter, $this->enclosure); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
foreach ($data as $item) { |
|
56
|
|
|
\fputcsv($handle, $item, $this->delimiter, $this->enclosure); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
\rewind($handle); |
|
60
|
|
|
|
|
61
|
|
|
$csvData = (string) \stream_get_contents($handle); |
|
62
|
|
|
|
|
63
|
|
|
\fclose($handle); |
|
64
|
|
|
|
|
65
|
|
|
return $csvData; |
|
66
|
|
|
} catch (\Throwable $e) { |
|
67
|
|
|
throw new FileException($e->getMessage()); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.