51 public static function csvToArray($input, $fieldDelimiter =
',', $fieldEnclosure =
'"', $maximumColumns = 0)
54 $maximumCellCount = 0;
56 if (($handle = fopen(
'php://memory',
'r+')) !==
false) {
57 fwrite($handle, $input);
59 while (($cells = fgetcsv($handle, 0, $fieldDelimiter, $fieldEnclosure)) !==
false) {
60 $maximumCellCount = max(count($cells), $maximumCellCount);
61 $multiArray[] = preg_replace(
'|<br */?>|i', LF, $cells);
66 if ($maximumColumns > $maximumCellCount) {
67 $maximumCellCount = $maximumColumns;
70 foreach ($multiArray as &$row) {
71 for ($key = 0; $key < $maximumCellCount; $key++) {
74 && $maximumColumns < $maximumCellCount
75 && $key >= $maximumColumns
77 if (isset($row[$key])) {
80 } elseif (!isset($row[$key])) {
98 public static function csvValues(array $row,
string $delim =
',',
string $quote =
'"',
int $type = self::TYPE_REMOVE_CONTROLS)
100 $resource = fopen(
'php://temp',
'w');
101 if (!is_resource($resource)) {
102 throw new \RuntimeException(
'Cannot open temporary data stream for writing', 1625556521);
105 array_map([self::class,
'assertCellValueType'], $row);
106 if ($type === self::TYPE_REMOVE_CONTROLS) {
107 $row = array_map([self::class,
'removeControlLiterals'], $row);
108 } elseif ($type === self::TYPE_PREFIX_CONTROLS) {
109 $row = array_map([self::class,
'prefixControlLiterals'], $row);
111 fputcsv($resource, $modifier($row), $delim, $quote);
113 $content = stream_get_contents($resource);
126 if (!self::shallFilterValue($cellValue)) {
129 $cellValue = (string)$cellValue;
130 return preg_replace(
'#^([\t\v=+*%/@-])#',
'\'${1}
', $cellValue);
140 protected static function removeControlLiterals($cellValue)
142 if (!self::shallFilterValue($cellValue)) {
145 $cellValue = (string)$cellValue;
146 return preg_replace('#^([\t\v=+*%/@-]+)+#
', '', $cellValue);
154 protected static function assertCellValueType($cellValue): void
156 // int, float, string, bool, null
157 if ($cellValue === null || is_scalar($cellValue)) {
160 throw new \RuntimeException(
161 sprintf('Unexpected type %s
for cell value
', gettype($cellValue)),
173 protected static function shallFilterValue($cellValue): bool
175 return $cellValue !== null
176 && !is_bool($cellValue)
177 && !is_numeric($cellValue)
178 && !MathUtility::canBeInterpretedAsInteger($cellValue)
179 && !MathUtility::canBeInterpretedAsFloat($cellValue);