BladeOne.php
2 years ago
CSV.php
9 months ago
Calculations.php
2 years ago
Currency.php
8 months ago
Device.php
1 year ago
Device_Cache.php
2 years ago
Dir.php
5 months ago
Format.php
5 months ago
Link_Validator.php
6 months ago
Number_Formatter.php
5 months ago
Obj.php
6 months ago
Request.php
11 months ago
Salt.php
1 year ago
Security.php
1 year ago
Server.php
2 years ago
Singleton.php
2 years ago
String_Util.php
2 years ago
Timezone.php
5 months ago
URL.php
6 months ago
WP_Async_Request.php
1 year ago
CSV.php
47 lines
| 1 | <?php |
| 2 | |
| 3 | namespace IAWP\Utils; |
| 4 | |
| 5 | use IAWPSCOPED\League\Csv\EscapeFormula; |
| 6 | /** @internal */ |
| 7 | class CSV |
| 8 | { |
| 9 | private array $header; |
| 10 | private array $rows; |
| 11 | private EscapeFormula $formatter; |
| 12 | /** |
| 13 | * @param array $header |
| 14 | * @param array[] $rows |
| 15 | */ |
| 16 | public function __construct(array $header, array $rows) |
| 17 | { |
| 18 | $this->header = $header; |
| 19 | $this->rows = $rows; |
| 20 | $this->formatter = new EscapeFormula(); |
| 21 | } |
| 22 | public function to_string() : string |
| 23 | { |
| 24 | $delimiter = ','; |
| 25 | $enclosure = '"'; |
| 26 | $escape_character = '\\'; |
| 27 | $temporary_file = \fopen('php://memory', 'r+'); |
| 28 | \fputcsv($temporary_file, $this->header, $delimiter, $enclosure, $escape_character); |
| 29 | foreach ($this->rows as $row) { |
| 30 | $row = $this->escape_row($row); |
| 31 | \fputcsv($temporary_file, $row, $delimiter, $enclosure, $escape_character); |
| 32 | } |
| 33 | \rewind($temporary_file); |
| 34 | return \stream_get_contents($temporary_file); |
| 35 | } |
| 36 | private function escape_row(array $row) : array |
| 37 | { |
| 38 | $row = $this->formatter->escapeRecord($row); |
| 39 | foreach ($row as &$cell) { |
| 40 | if ($cell === "'-") { |
| 41 | $cell = '-'; |
| 42 | } |
| 43 | } |
| 44 | return $row; |
| 45 | } |
| 46 | } |
| 47 |