2013-07-12 06:02:51 -04:00
|
|
|
<?php
|
2026-03-26 12:46:27 -04:00
|
|
|
|
|
|
|
|
// SPDX-FileCopyrightText: 2018 Icinga GmbH <https://icinga.com>
|
|
|
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
2013-07-12 06:02:51 -04:00
|
|
|
|
|
|
|
|
namespace Icinga\File;
|
|
|
|
|
|
2016-10-11 03:53:21 -04:00
|
|
|
use Traversable;
|
|
|
|
|
|
2013-07-12 06:02:51 -04:00
|
|
|
class Csv
|
|
|
|
|
{
|
|
|
|
|
protected $query;
|
|
|
|
|
|
2017-01-27 08:48:59 -05:00
|
|
|
protected function __construct()
|
|
|
|
|
{
|
|
|
|
|
}
|
2013-07-12 06:02:51 -04:00
|
|
|
|
2016-10-11 03:53:21 -04:00
|
|
|
public static function fromQuery(Traversable $query)
|
2013-07-12 06:02:51 -04:00
|
|
|
{
|
2016-10-11 03:53:21 -04:00
|
|
|
$csv = new static();
|
2013-07-12 06:02:51 -04:00
|
|
|
$csv->query = $query;
|
|
|
|
|
return $csv;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function dump()
|
|
|
|
|
{
|
|
|
|
|
header('Content-type: text/csv');
|
2013-09-04 12:27:16 -04:00
|
|
|
echo (string) $this;
|
2013-07-12 06:02:51 -04:00
|
|
|
}
|
2013-09-04 12:27:16 -04:00
|
|
|
|
2013-07-12 06:02:51 -04:00
|
|
|
public function __toString()
|
|
|
|
|
{
|
|
|
|
|
$first = true;
|
|
|
|
|
$csv = '';
|
2016-10-11 03:53:21 -04:00
|
|
|
foreach ($this->query as $row) {
|
2013-07-12 06:02:51 -04:00
|
|
|
if ($first) {
|
|
|
|
|
$csv .= implode(',', array_keys((array) $row)) . "\r\n";
|
|
|
|
|
$first = false;
|
|
|
|
|
}
|
|
|
|
|
$out = array();
|
|
|
|
|
foreach ($row as & $val) {
|
2025-04-07 07:46:21 -04:00
|
|
|
$out[] = '"' . ($val == '0' ? '0' : ($val ? str_replace('"', '""', $val) : '')) . '"';
|
2013-07-12 06:02:51 -04:00
|
|
|
}
|
|
|
|
|
$csv .= implode(',', $out) . "\r\n";
|
|
|
|
|
}
|
2014-04-23 08:40:39 -04:00
|
|
|
|
2013-07-12 06:02:51 -04:00
|
|
|
return $csv;
|
|
|
|
|
}
|
|
|
|
|
}
|