Issues (52)

src/InputSources/InlineInputSource.php (1 issue)

Severity
1
<?php
2
declare(strict_types=1);
3
4
namespace Level23\Druid\InputSources;
5
6
use Exception;
7
8
class InlineInputSource implements InputSourceInterface
9
{
10
    protected string $data;
11
12
    /**
13
     * InlineInputSource constructor.
14
     *
15
     * @param string $data
16
     */
17 1
    public function __construct(string $data)
18
    {
19 1
        $this->data = $data;
20
    }
21
22
    /**
23
     * @return array<string,string>
24
     */
25 1
    public function toArray(): array
26
    {
27 1
        return [
28 1
            'type' => 'inline',
29 1
            'data' => $this->data,
30 1
        ];
31
    }
32
33
    /**
34
     * Helper method to convert array to a json string.
35
     *
36
     * @param array<array<string|int|float|bool|null|array<mixed>>> $data
37
     *
38
     * @return string
39
     */
40 1
    public static function dataToJson(array $data): string
41
    {
42 1
        return implode("\n", array_map(fn($elem) => json_encode($elem), $data));
43
    }
44
45
    /**
46
     * Helper method to convert an array to a csv string.
47
     *
48
     * @param array<array<string|int|float|bool|null>> $data
49
     * @param string                                   $separator
50
     * @param string                                   $enclosure
51
     * @param string                                   $escape
52
     *
53
     * @return string
54
     * @throws \Exception
55
     */
56 1
    public static function dataToCsv(
57
        array $data,
58
        string $separator = ",",
59
        string $enclosure = '"',
60
        string $escape = "\\"
61
    ): string {
62 1
        $f = fopen('php://memory', 'r+');
63 1
        if (!$f) {
0 ignored issues
show
$f is of type resource, thus it always evaluated to false.
Loading history...
64
            throw new Exception('Failed to convert data to csv'); // @codeCoverageIgnore
65
        }
66 1
        foreach ($data as $row) {
67 1
            fputcsv($f, $row, $separator, $enclosure, $escape);
68
        }
69 1
        rewind($f);
70
71 1
        $content = stream_get_contents($f);
72 1
        if ($content === false) {
73
            throw new Exception('Failed to convert data to csv'); // @codeCoverageIgnore
74
        }
75 1
        fclose($f);
76
77 1
        return $content;
78
    }
79
}