1 | <?php |
||
2 | declare(strict_types=1); |
||
3 | /** |
||
4 | * CsvExporter.php |
||
5 | * Copyright (c) 2017 [email protected] |
||
6 | * |
||
7 | * This file is part of Firefly III. |
||
8 | * |
||
9 | * Firefly III is free software: you can redistribute it and/or modify |
||
10 | * it under the terms of the GNU General Public License as published by |
||
11 | * the Free Software Foundation, either version 3 of the License, or |
||
12 | * (at your option) any later version. |
||
13 | * |
||
14 | * Firefly III is distributed in the hope that it will be useful, |
||
15 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
||
16 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
||
17 | * GNU General Public License for more details. |
||
18 | * |
||
19 | * You should have received a copy of the GNU General Public License |
||
20 | * along with Firefly III. If not, see <http://www.gnu.org/licenses/>. |
||
21 | */ |
||
22 | |||
23 | namespace FireflyIII\Export\Exporter; |
||
24 | |||
25 | use FireflyIII\Export\Entry\Entry; |
||
26 | use League\Csv\Writer; |
||
27 | use Storage; |
||
28 | |||
29 | /** |
||
30 | * Class CsvExporter. |
||
31 | */ |
||
32 | class CsvExporter extends BasicExporter implements ExporterInterface |
||
33 | { |
||
34 | /** @var string */ |
||
35 | private $fileName; |
||
36 | |||
37 | /** |
||
38 | * @return string |
||
39 | */ |
||
40 | public function getFileName(): string |
||
41 | { |
||
42 | return $this->fileName; |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * @return bool |
||
47 | * |
||
48 | */ |
||
49 | public function run(): bool |
||
50 | { |
||
51 | // create temporary file: |
||
52 | $this->tempFile(); |
||
53 | |||
54 | // necessary for CSV writer: |
||
55 | $fullPath = storage_path('export') . DIRECTORY_SEPARATOR . $this->fileName; |
||
56 | |||
57 | |||
58 | //we create the CSV into memory |
||
59 | $writer = Writer::createFromPath($fullPath); |
||
60 | $rows = []; |
||
61 | |||
62 | // get field names for header row: |
||
63 | $first = $this->getEntries()->first(); |
||
64 | $headers = []; |
||
65 | if (null !== $first) { |
||
66 | $headers = array_keys(get_object_vars($first)); |
||
67 | } |
||
68 | |||
69 | $rows[] = $headers; |
||
70 | |||
71 | /** @var Entry $entry */ |
||
72 | foreach ($this->getEntries() as $entry) { |
||
73 | $line = []; |
||
74 | foreach ($headers as $header) { |
||
75 | $line[] = $entry->$header; |
||
76 | } |
||
77 | $rows[] = $line; |
||
78 | } |
||
79 | $writer->insertAll($rows); |
||
80 | |||
81 | return true; |
||
82 | } |
||
83 | |||
84 | private function tempFile() |
||
85 | { |
||
86 | $this->fileName = $this->job->key . '-records.csv'; |
||
87 | // touch file in export directory: |
||
88 | $disk = Storage::disk('export'); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
Loading history...
|
|||
89 | $disk->put($this->fileName, ''); |
||
90 | } |
||
91 | } |
||
92 |