CsvCreator::getCsvData()   B
last analyzed

Complexity

Conditions 7
Paths 37

Size

Total Lines 36
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 19
c 3
b 0
f 0
dl 0
loc 36
rs 8.8333
cc 7
nc 37
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace WebServCo\Framework\Files;
6
7
use WebServCo\Framework\Exceptions\FileException;
8
9
final class CsvCreator
10
{
11
    protected string $delimiter;
12
    protected string $enclosure;
13
14
    public function __construct(string $delimiter = ',', string $enclosure = '"')
15
    {
16
        $this->delimiter = $delimiter;
17
        $this->enclosure = $enclosure;
18
    }
19
20
    /**
21
    * @param array<int,array<mixed>> $data
22
    */
23
    public function getCsvFile(string $fileName, array $data, bool $addHeader = true): CsvFile
24
    {
25
        $csvData = $this->getCsvData($data, $addHeader);
26
        return new CsvFile($fileName, $csvData);
27
    }
28
29
    /**
30
    * @param array<int,array<mixed>> $data
31
    */
32
    public function getCsvData(array $data, bool $addHeader = true): string
33
    {
34
        if (!$data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array<integer,array<mixed,mixed>> is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
35
            return '';
36
        }
37
        try {
38
            // temporary file/memory wrapper; if bigger than 5MB will be written to temp file.
39
            $handle = \fopen('php://temp/maxmemory:' . (5 * 1024 * 1024), 'r+');
40
41
            if (!\is_resource($handle)) {
42
                throw new FileException('Not a valid resource.');
43
            }
44
45
            // Add Byte Order mark (BOM) for UTF-8.
46
            \fwrite($handle, \chr(0xEF) . \chr(0xBB) . \chr(0xBF));
47
48
            if ($addHeader) {
49
                $headerData = \current($data);
50
                if (false !== $headerData) {
51
                    \fputcsv($handle, \array_keys($headerData), $this->delimiter, $this->enclosure);
52
                }
53
            }
54
55
            foreach ($data as $item) {
56
                \fputcsv($handle, $item, $this->delimiter, $this->enclosure);
57
            }
58
59
            \rewind($handle);
60
61
            $csvData = (string) \stream_get_contents($handle);
62
63
            \fclose($handle);
64
65
            return $csvData;
66
        } catch (\Throwable $e) {
67
            throw new FileException($e->getMessage());
68
        }
69
    }
70
}
71