1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ridibooks\Platform\Common; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\HttpFoundation\Response; |
6
|
|
|
|
7
|
|
|
class CsvResponse extends Response |
8
|
|
|
{ |
9
|
|
|
const UTF8_BOM = "\xEF\xBB\xBF"; |
10
|
|
|
private $format_large_number_as_string; |
11
|
|
|
|
12
|
|
|
public function __construct( |
13
|
|
|
$data = [], |
14
|
|
|
$filename = null, |
15
|
|
|
$format_large_number_as_string = false, |
16
|
|
|
$status = 200, |
17
|
|
|
$headers = [] |
18
|
|
|
) { |
19
|
|
|
parent::__construct('', $status, $headers); |
20
|
|
|
|
21
|
|
|
if (null === $filename) { |
22
|
|
|
$filename = "data_" . date('Ymd'); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
$this->format_large_number_as_string = $format_large_number_as_string; |
26
|
|
|
self::setExcelHeader($filename); |
27
|
|
|
$this->setData($data); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public static function create( |
31
|
|
|
$data = [], |
32
|
|
|
$filename = null, |
33
|
|
|
$format_large_number_as_string = false, |
34
|
|
|
$status = 200, |
35
|
|
|
$headers = [] |
36
|
|
|
) { |
37
|
|
|
return new static($data, $filename, $format_large_number_as_string, $status, $headers); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
private function setData($data) |
41
|
|
|
{ |
42
|
|
|
foreach ($data as $k => $v) { |
43
|
|
|
if (is_object($v)) { |
44
|
|
|
$v = get_object_vars($v); |
45
|
|
|
} elseif (is_scalar($v)) { |
46
|
|
|
$v = [$v]; |
47
|
|
|
} |
48
|
|
|
foreach ($v as $k2 => $v2) { |
49
|
|
|
$v[$k2] = $v2; |
50
|
|
|
} |
51
|
|
|
$data[$k] = $v; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$this->setContent(self::UTF8_BOM . $this->escapeQuotesAddNewLine($data)); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
private function escapeQuotesAddNewLine($data) |
58
|
|
|
{ |
59
|
|
|
$new_data = []; |
60
|
|
|
foreach ($data as $row) { |
61
|
|
|
$new_row = []; |
62
|
|
|
foreach ($row as $cell) { |
63
|
|
|
$formatted_cell = '"' . str_replace('"', '""', $cell) . '"'; |
64
|
|
|
if ($this->format_large_number_as_string && ctype_digit($cell) && intval($cell) > pow(10, 8)) { |
65
|
|
|
// 1E+xx 형태로 표시되는 문제를 해결하기 위해 아주 큰 숫자는 string으로 취급 |
66
|
|
|
$formatted_cell = '=' . $formatted_cell; |
67
|
|
|
} |
68
|
|
|
$new_row[] = $formatted_cell; |
69
|
|
|
} |
70
|
|
|
$new_data[] = implode(",", $new_row); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return implode("\r\n", $new_data); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param $file_name |
78
|
|
|
*/ |
79
|
|
|
private static function setExcelHeader($file_name) |
80
|
|
|
{ |
81
|
|
|
header("Content-Type: application/csv; charset=utf-8"); |
82
|
|
|
header("Content-Disposition: attachment; filename=\"$file_name.csv\""); |
83
|
|
|
header('Cache-Control: max-age=0'); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|