-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollection.php
62 lines (49 loc) · 1.23 KB
/
Collection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?php
namespace Orchestra\Support;
use Illuminate\Support\Collection as BaseCollection;
use Orchestra\Contracts\Support\Transformable;
use Orchestra\Support\Contracts\Csvable;
class Collection extends BaseCollection implements Csvable, Transformable
{
/**
* {@inheritdoc}
*/
public function toCsv(): string
{
\ob_start();
$stream = $this->streamCsv();
\fclose($stream);
return \ob_get_clean();
}
/**
* Stream CSV output.
*
* @return object
*/
public function streamCsv()
{
$delimiter = ',';
$enclosure = '"';
$header = $this->resolveCsvHeader();
$stream = \fopen('php://output', 'r+');
\fputcsv($stream, $header, $delimiter, $enclosure);
foreach ($this->items as $key => $item) {
\fputcsv($stream, Arr::dot($item), $delimiter, $enclosure);
}
return $stream;
}
/**
* Resolve CSV header.
*
* @return array
*/
protected function resolveCsvHeader(): array
{
$header = [];
if (! $this->isEmpty()) {
$single = $this->first();
$header = \array_keys(Arr::dot($single));
}
return $header;
}
}