2013-07-12 12:02:51 +02:00
|
|
|
<?php
|
2016-02-08 15:41:00 +01:00
|
|
|
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */
|
2013-07-12 12:02:51 +02:00
|
|
|
|
|
|
|
namespace Icinga\File;
|
|
|
|
|
2016-10-11 09:53:21 +02:00
|
|
|
use Traversable;
|
|
|
|
|
2013-07-12 12:02:51 +02:00
|
|
|
class Csv
|
|
|
|
{
|
|
|
|
protected $query;
|
|
|
|
|
2017-01-27 14:48:59 +01:00
|
|
|
protected function __construct()
|
|
|
|
{
|
|
|
|
}
|
2013-07-12 12:02:51 +02:00
|
|
|
|
2016-10-11 09:53:21 +02:00
|
|
|
public static function fromQuery(Traversable $query)
|
2013-07-12 12:02:51 +02:00
|
|
|
{
|
2016-10-11 09:53:21 +02:00
|
|
|
$csv = new static();
|
2013-07-12 12:02:51 +02:00
|
|
|
$csv->query = $query;
|
|
|
|
return $csv;
|
|
|
|
}
|
|
|
|
|
|
|
|
public function dump()
|
|
|
|
{
|
|
|
|
header('Content-type: text/csv');
|
2013-09-04 18:27:16 +02:00
|
|
|
echo (string) $this;
|
2013-07-12 12:02:51 +02:00
|
|
|
}
|
2013-09-04 18:27:16 +02:00
|
|
|
|
2013-07-12 12:02:51 +02:00
|
|
|
public function __toString()
|
|
|
|
{
|
|
|
|
$first = true;
|
|
|
|
$csv = '';
|
2016-10-11 09:53:21 +02:00
|
|
|
foreach ($this->query as $row) {
|
2013-07-12 12:02:51 +02:00
|
|
|
if ($first) {
|
|
|
|
$csv .= implode(',', array_keys((array) $row)) . "\r\n";
|
|
|
|
$first = false;
|
|
|
|
}
|
|
|
|
$out = array();
|
|
|
|
foreach ($row as & $val) {
|
|
|
|
$out[] = '"' . $val . '"';
|
|
|
|
}
|
|
|
|
$csv .= implode(',', $out) . "\r\n";
|
|
|
|
}
|
2014-04-23 14:40:39 +02:00
|
|
|
|
2013-07-12 12:02:51 +02:00
|
|
|
return $csv;
|
|
|
|
}
|
|
|
|
}
|