CsvService::writeContent()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 8
c 2
b 0
f 0
dl 0
loc 16
rs 10
cc 2
nc 2
nop 3
1
<?php
2
3
/*
4
 * This file is part of the TheAlternativeZurich/events project.
5
 *
6
 * (c) Florian Moser <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace App\Service;
13
14
use App\Service\Interfaces\CsvServiceInterface;
15
use Symfony\Component\HttpFoundation\Response;
16
use Symfony\Component\HttpFoundation\StreamedResponse;
17
18
class CsvService implements CsvServiceInterface
19
{
20
    const DELIMITER = "\t";
21
22
    /**
23
     * creates a response containing the data rendered as a csv.
24
     *
25
     * @param string[][] $data
26
     * @param string[]   $header
27
     */
28
    public function streamCsv(string $filename, array $data, array $header): Response
29
    {
30
        $response = new StreamedResponse();
31
        $response->setCallback(function () use ($header, $data) {
32
            $handle = fopen('php://output', 'w+');
33
            if (false === $handle) {
34
                throw new \Exception('could not write to output');
35
            }
36
37
            $this->writeContent($handle, $data, $header);
38
39
            fclose($handle);
40
        });
41
42
        $response->setStatusCode(200);
43
        $response->headers->set('Content-Type', 'text/csv; charset=utf-8');
44
        $response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"');
45
46
        return $response;
47
    }
48
49
    /**
50
     * @param resource   $handle
51
     * @param string[][] $data
52
     * @param string[]   $header
53
     */
54
    private function writeContent($handle, array $data, array $header)
55
    {
56
        //UTF-8 BOM
57
        fwrite($handle, "\xEF\xBB\xBF");
58
        //set delimiter to specified
59
        fwrite($handle, 'sep='.static::DELIMITER."\n");
60
61
        // Add the header of the CSV file
62
        fputcsv($handle, $header, static::DELIMITER);
63
64
        //add the data
65
        foreach ($data as $row) {
66
            fputcsv(
67
                $handle, // The file pointer
68
                $row, // The fields
69
                static::DELIMITER // The delimiter
70
            );
71
        }
72
    }
73
}
74