CsvExporter::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Fowp\WordPressPluginRetriever\Export;
4
5
/**
6
 * This exporter writes the retrieved plugins to a given CSV file.
7
 *
8
 * @author [email protected]
9
 */
10
class CsvExporter implements Exporter
11
{
12
    /**
13
     * The file resource of the opened CSV file
14
     *
15
     * @var resource
16
     */
17
    private $fileHandle;
18
19
    /**
20
     * True if it is the first run. We need that property as with the first run
21
     * we have to write the CSV header.
22
     *
23
     * @var bool
24
     */
25
    private bool $firstRun = true;
26
27
    /**
28
     * @param string $filename
29
     * @param string $fileMode
30
     */
31
    public function __construct(string $filename, string $fileMode = 'w')
32
    {
33
        $this->fileHandle = fopen($filename, $fileMode);
34
    }
35
36
    /**
37
     * @inheritDoc
38
     */
39
    public function process(array $pluginBlock, int $currentPage, int $maxPages): void
40
    {
41
        foreach ($pluginBlock as $plugin) {
42
            if ($this->firstRun) {
43
                $this->firstRun = false;
44
                fputcsv($this->fileHandle, array_keys($plugin));
45
            }
46
47
            $plugin['requires_plugins'] = implode(', ', $plugin['requires_plugins']);
48
            $plugin['tags'] = implode(', ', $plugin['tags']);
49
50
            $plugin['ratings'] = json_encode($plugin['ratings']);
51
            $plugin['icons'] = json_encode($plugin['icons']);
52
53
            fputcsv($this->fileHandle, $plugin);
54
        }
55
    }
56
57
    /**
58
     * @inheritDoc
59
     */
60
    public function finish(): void
61
    {
62
        fclose($this->fileHandle);
63
    }
64
}
65