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

89 lines
2.3 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;
2016-04-26 05:39:29 -05:00
use FireflyIII\Export\Entry\Entry;
2016-02-04 10:16:16 -06:00
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:
2016-04-26 13:49:22 -05:00
$rows[] = array_keys(Entry::getFieldsAndTypes());
2016-02-04 10:16:16 -06:00
// then the rest:
/** @var Entry $entry */
foreach ($this->getEntries() as $entry) {
2016-04-26 13:49:22 -05:00
// order is defined in Entry::getFieldsAndTypes.
$rows[] = [
$entry->description, $entry->amount, $entry->date, $entry->sourceAccount->id, $entry->sourceAccount->name, $entry->sourceAccount->iban,
$entry->sourceAccount->type, $entry->sourceAccount->number, $entry->destinationAccount->id, $entry->destinationAccount->name,
$entry->destinationAccount->iban, $entry->destinationAccount->type, $entry->destinationAccount->number, $entry->budget->id,
$entry->budget->name, $entry->category->id, $entry->category->name, $entry->bill->id, $entry->bill->name,
];
2016-02-04 10:16:16 -06:00
}
$writer->insertAll($rows);
2016-04-25 11:43:09 -05:00
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
}