firefly-iii/app/Export/Exporter/CsvExporter.php

83 lines
1.7 KiB
PHP
Raw Normal View History

2016-02-04 10:16:16 -06:00
<?php
2016-02-05 05:08:25 -06:00
declare(strict_types = 1);
2016-02-04 10:16:16 -06:00
/**
* CsvExporter.php
2016-04-01 09:44:46 -05:00
* Copyright (C) 2016 thegrumpydictator@gmail.com
2016-02-04 10:16:16 -06:00
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace FireflyIII\Export\Exporter;
use FireflyIII\Export\Entry;
use FireflyIII\Models\ExportJob;
use League\Csv\Writer;
use SplFileObject;
/**
* Class CsvExporter
*
* @package FireflyIII\Export\Exporter
*/
class CsvExporter extends BasicExporter implements ExporterInterface
{
/** @var string */
private $fileName;
/**
* CsvExporter constructor.
2016-02-05 08:41:40 -06:00
*
* @param ExportJob $job
2016-02-04 10:16:16 -06:00
*/
public function __construct(ExportJob $job)
{
parent::__construct($job);
2016-02-23 00:27:29 -06:00
2016-02-04 10:16:16 -06:00
}
/**
* @return string
*/
2016-04-06 09:37:28 -05:00
public function getFileName(): string
2016-02-04 10:16:16 -06:00
{
return $this->fileName;
}
/**
2016-04-06 09:37:28 -05:00
* @return bool
2016-02-04 10:16:16 -06:00
*/
2016-04-06 09:37:28 -05:00
public function run(): bool
2016-02-04 10:16:16 -06:00
{
// create temporary file:
$this->tempFile();
2016-02-23 00:27:29 -06:00
// necessary for CSV writer:
$fullPath = storage_path('export') . DIRECTORY_SEPARATOR . $this->fileName;
2016-02-04 10:16:16 -06:00
// create CSV writer:
2016-02-23 00:27:29 -06:00
$writer = Writer::createFromPath(new SplFileObject($fullPath, 'a+'), 'w');
2016-02-04 10:16:16 -06:00
// all rows:
$rows = [];
// add header:
$first = $this->getEntries()->first();
$rows[] = array_keys(get_object_vars($first));
// then the rest:
/** @var Entry $entry */
foreach ($this->getEntries() as $entry) {
$rows[] = array_values(get_object_vars($entry));
}
$writer->insertAll($rows);
2016-04-06 09:37:28 -05:00
return true;
2016-02-04 10:16:16 -06:00
}
private function tempFile()
{
2016-02-23 00:27:29 -06:00
$this->fileName = $this->job->key . '-records.csv';
2016-02-04 10:16:16 -06:00
}
2016-02-10 09:01:18 -06:00
}