Passed
Push — master ( c85748...2fd0ab )
by Petr
08:11
created

Csv::pack()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 10
ccs 8
cts 8
cp 1
crap 2
rs 10
1
<?php
2
3
namespace kalanis\kw_mapper\Storage\Shared\FormatFiles;
4
5
6
use kalanis\kw_mapper\Interfaces\IFileFormat;
7
8
9
/**
10
 * Class Csv
11
 * @package kalanis\kw_mapper\Storage\Shared\FormatFiles
12
 * Store it in CSV table
13
 */
14
class Csv implements IFileFormat
15
{
16
    use TNl;
17
18
    /** @var string */
19
    protected $delimitLines = PHP_EOL;
20
21 1
    public function setDelimiters(string $lines = PHP_EOL): self
22
    {
23 1
        $this->delimitLines = $lines;
24 1
        return $this;
25
    }
26
27 1
    public function unpack(string $content): array
28
    {
29 1
        $lines = str_getcsv($content, $this->delimitLines); //parse the rows
30 1
        $records = [];
31 1
        foreach ($lines as &$line) {
32 1
            if (empty($line)) {
33 1
                continue;
34
            }
35
36 1
            $records[] = array_map([$this, 'unescapeNl'], str_getcsv($line));
37
        }
38 1
        return $records;
39
    }
40
41 1
    public function pack(array $records): string
42
    {
43 1
        $lines = [];
44 1
        foreach ($records as &$record) {
45 1
            $record = (array) $record;
46 1
            ksort($record);
47 1
            $record[] = ''; // separator on end
48 1
            $lines[] = $this->str_putcsv(array_map([$this, 'escapeNl'], $record));
49
        }
50 1
        return implode($this->delimitLines, $lines);
51
    }
52
53
    /**
54
     * @param array<string|int, string|int|float|array<string|int, string|int>> $array
55
     * @param string $delimiter
56
     * @param string $enclosure
57
     * @param string $terminator
58
     * @return string
59
     * @link https://www.php.net/manual/en/function.str-getcsv.php#88353
60
     * @codeCoverageIgnore better try it live
61
     */
62
    protected function str_putcsv($array, $delimiter = ',', $enclosure = '"', $terminator = "\n") {
63
        # First convert associative array to numeric indexed array
64
        $workArray = [];
65
        foreach ($array as $key => $value) {
66
            $workArray[] = $value;
67
        }
68
69
        $returnString = '';                 # Initialize return string
70
        $arraySize = count($workArray);     # Get size of array
71
72
        for ($i=0; $i<$arraySize; $i++) {
73
            # Nested array, process nest item
74
            if (is_array($workArray[$i])) {
75
                $returnString .= $this->str_putcsv($workArray[$i], $delimiter, $enclosure, $terminator);
76
            } else {
77
                switch (gettype($workArray[$i])) {
78
                    # Manually set some strings
79
                    case "NULL":     $_spFormat = ''; break;
80
                    case "boolean":  $_spFormat = (true == $workArray[$i]) ? 'true': 'false'; break;
81
                    # Make sure sprintf has a good datatype to work with
82
                    case "integer":  $_spFormat = '%i'; break;
83
                    case "double":   $_spFormat = '%0.2f'; break;
84
                    case "string":   $_spFormat = '%s'; break;
85
                    # Unknown or invalid items for a csv - note: the datatype of array is already handled above, assuming the data is nested
86
                    case "object":
87
                    case "resource":
88
                    default:         $_spFormat = ''; break;
89
                }
90
                $returnString .= sprintf('%2$s'.$_spFormat.'%2$s', $workArray[$i], $enclosure);
91
                $returnString .= ($i < ($arraySize-1)) ? $delimiter : $terminator;
92
            }
93
        }
94
        # Done the workload, return the output information
95
        return $returnString;
96
    }
97
98
}
99