Completed
Push — master ( 2242cd...489a99 )
by Ryan
07:43
created

Export   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
c 2
b 0
f 0
lcom 0
cbo 3
dl 0
loc 45
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B handle() 0 34 4
1
<?php namespace Anomaly\Streams\Platform\Ui\Table\Component\Action\Handler;
2
3
use Anomaly\Streams\Platform\Model\EloquentModel;
4
use Anomaly\Streams\Platform\Ui\Table\Component\Action\ActionHandler;
5
use Anomaly\Streams\Platform\Ui\Table\TableBuilder;
6
use Illuminate\Contracts\Bus\SelfHandling;
7
use Illuminate\Routing\ResponseFactory;
8
9
/**
10
 * Class Export
11
 *
12
 * @link          http://anomaly.is/streams-platform
13
 * @author        AnomalyLabs, Inc. <[email protected]>
14
 * @author        Ryan Thompson <[email protected]>
15
 * @package       Anomaly\Streams\Platform\Ui\Table\Component\Action\Handler
16
 */
17
class Export extends ActionHandler implements SelfHandling
18
{
19
20
    /**
21
     * Export the selected entries.
22
     *
23
     * @param TableBuilder    $builder
24
     * @param ResponseFactory $response
25
     * @param array           $selected
26
     */
27
    public function handle(TableBuilder $builder, ResponseFactory $response, array $selected)
28
    {
29
        $model  = $builder->getTableModel();
30
        $stream = $builder->getTableStream();
31
32
        $headers = [
33
            'Content-Disposition' => 'attachment; filename=' . $stream->getSlug() . '.csv',
34
            'Cache-Control'       => 'must-revalidate, post-check=0, pre-check=0',
35
            'Content-type'        => 'text/csv',
36
            'Pragma'              => 'public',
37
            'Expires'             => '0'
38
        ];
39
40
        $callback = function () use ($selected, $model) {
41
42
            $output = fopen('php://output', 'w');
43
44
            /* @var EloquentModel $entry */
45
            foreach ($selected as $k => $id) {
46
                if ($entry = $model->find($id)) {
47
48
                    if ($k == 0) {
49
                        fputcsv($output, array_keys($entry->toArray()));
50
                    }
51
52
                    fputcsv($output, $entry->toArray());
53
                }
54
            }
55
56
            fclose($output);
57
        };
58
59
        $builder->setTableResponse($response->stream($callback, 200, $headers));
60
    }
61
}
62