1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Smart\EtlBundle\Utils; |
4
|
|
|
|
5
|
|
|
use Smart\EtlBundle\Exception\Utils\ArrayUtils\MultiArrayNbMaxRowsException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* @author Mathieu Ducrot <[email protected]> |
9
|
|
|
*/ |
10
|
|
|
class ArrayUtils |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* Clean data from an array |
14
|
|
|
* - remove null value and empty string |
15
|
|
|
*/ |
16
|
|
|
public static function removeEmpty(array $array): array |
17
|
|
|
{ |
18
|
|
|
return array_filter($array, function ($item) { |
19
|
|
|
return $item !== null && (!is_string($item) || $item !== ''); |
20
|
|
|
}); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Convert and clean data from string to array |
25
|
|
|
*/ |
26
|
|
|
public static function getArrayFromString(?string $string): array |
27
|
|
|
{ |
28
|
|
|
$toReturn = explode(PHP_EOL, $string); |
|
|
|
|
29
|
|
|
$toReturn = array_map(function ($row) { |
30
|
|
|
return trim($row); |
31
|
|
|
}, $toReturn); |
32
|
|
|
|
33
|
|
|
return array_unique(self::removeEmpty($toReturn)); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Convert and clean data from string to a multidimensional array |
38
|
|
|
* |
39
|
|
|
* @param array $options (Optional) To pass field separator and nb max row |
40
|
|
|
* @throws MultiArrayNbMaxRowsException |
41
|
|
|
*/ |
42
|
|
|
public static function getMultiArrayFromString(string $string, array $header, array $options = []): array |
43
|
|
|
{ |
44
|
|
|
$nbRows = StringUtils::countRows($string); |
45
|
|
|
if (isset($options['nb_max_row']) && $nbRows > $options['nb_max_row']) { |
46
|
|
|
throw new MultiArrayNbMaxRowsException($options['nb_max_row'], $nbRows); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$toReturn = self::getArrayFromString($string); |
50
|
|
|
|
51
|
|
|
$delimiter = $options['delimiter'] ?? ','; |
52
|
|
|
$nbHeader = count($header); |
53
|
|
|
foreach ($toReturn as $key => $row) { |
54
|
|
|
$rowData = str_getcsv($row, $delimiter); |
55
|
|
|
|
56
|
|
|
$rowData = array_map(function ($data) { |
57
|
|
|
if ($data !== null) { |
58
|
|
|
$data = trim($data); |
59
|
|
|
|
60
|
|
|
if ($data === '') { |
61
|
|
|
$data = null; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return $data; |
66
|
|
|
}, $rowData); |
67
|
|
|
|
68
|
|
|
// fill missing field on the row with null values |
69
|
|
|
$rowData = array_pad($rowData, $nbHeader, null); |
70
|
|
|
// slice extra data on the row |
71
|
|
|
$rowData = array_slice($rowData, 0, $nbHeader); |
72
|
|
|
// combine to form the multidimensional array |
73
|
|
|
$toReturn[$key] = array_combine($header, $rowData); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $toReturn; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|