CsvUtility.php 5.95 KB
Newer Older
1
<?php
2

3
4
declare(strict_types=1);

5
6
7
8
9
10
11
12
13
14
15
16
17
/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

18
19
namespace TYPO3\CMS\Core\Utility;

20
21
use TYPO3\CMS\Core\IO\CsvStreamFilter;

22
23
24
/**
 * Class with helper functions for CSV handling
 */
25
26
class CsvUtility
{
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
    /**
     * whether to passthrough data as is, without any modification
     */
    public const TYPE_PASSTHROUGH = 0;

    /**
     * whether to remove control characters like `=`, `+`, ...
     */
    public const TYPE_REMOVE_CONTROLS = 1;

    /**
     * whether to prefix control characters like `=`, `+`, ...
     * to become `'=`, `'+`, ...
     */
    public const TYPE_PREFIX_CONTROLS = 2;

43
    /**
44
     * Convert a string, formatted as CSV, into a multidimensional array
45
46
47
48
49
50
51
52
53
     *
     * This cannot be done by str_getcsv, since it's impossible to handle enclosed cells with a line feed in it
     *
     * @param string $input The CSV input
     * @param string $fieldDelimiter The field delimiter
     * @param string $fieldEnclosure The field enclosure
     * @param int $maximumColumns The maximum amount of columns
     * @return array
     */
54
    public static function csvToArray(string $input, string $fieldDelimiter = ',', string $fieldEnclosure = '"', int $maximumColumns = 0): array
55
    {
56
        $multiArray = [];
57
        $maximumCellCount = 0;
58

59
60
61
62
        if (($handle = fopen('php://memory', 'r+')) !== false) {
            fwrite($handle, $input);
            rewind($handle);
            while (($cells = fgetcsv($handle, 0, $fieldDelimiter, $fieldEnclosure)) !== false) {
63
                $cells = is_array($cells) ? $cells : [];
64
                $maximumCellCount = max(count($cells), $maximumCellCount);
65
                $multiArray[] = preg_replace('|<br */?>|i', LF, $cells);
66
67
68
            }
            fclose($handle);
        }
69

70
71
72
        if ($maximumColumns > $maximumCellCount) {
            $maximumCellCount = $maximumColumns;
        }
73

74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
        foreach ($multiArray as &$row) {
            for ($key = 0; $key < $maximumCellCount; $key++) {
                if (
                    $maximumColumns > 0
                    && $maximumColumns < $maximumCellCount
                    && $key >= $maximumColumns
                ) {
                    if (isset($row[$key])) {
                        unset($row[$key]);
                    }
                } elseif (!isset($row[$key])) {
                    $row[$key] = '';
                }
            }
        }
89

90
91
        return $multiArray;
    }
92
93
94
95

    /**
     * Takes a row and returns a CSV string of the values with $delim (default is ,) and $quote (default is ") as separator chars.
     *
96
     * @param string[] $row Input array of values
97
98
     * @param string $delim Delimited, default is comma
     * @param string $quote Quote-character to wrap around the values.
99
     * @param int $type Output behaviour concerning potentially harmful control literals
100
101
     * @return string A single line of CSV
     */
102
    public static function csvValues(array $row, string $delim = ',', string $quote = '"', int $type = self::TYPE_REMOVE_CONTROLS): string
103
104
105
106
107
108
    {
        $resource = fopen('php://temp', 'w');
        if (!is_resource($resource)) {
            throw new \RuntimeException('Cannot open temporary data stream for writing', 1625556521);
        }
        $modifier = CsvStreamFilter::applyStreamFilter($resource, false);
109
        array_map(self::assertCellValueType(...), $row);
110
        if ($type === self::TYPE_REMOVE_CONTROLS) {
111
            $row = array_map(self::removeControlLiterals(...), $row);
112
        } elseif ($type === self::TYPE_PREFIX_CONTROLS) {
113
            $row = array_map(self::prefixControlLiterals(...), $row);
114
115
116
        }
        fputcsv($resource, $modifier($row), $delim, $quote);
        fseek($resource, 0);
117
        return stream_get_contents($resource);
118
119
120
121
122
    }

    /**
     * Prefixes control literals at the beginning of a cell value with a single quote
     *
123
     * (e.g. `=+value` --> `'=+value`)
124
     */
125
    protected static function prefixControlLiterals(bool|int|float|string|null $cellValue): bool|int|float|string|null
126
127
128
129
130
131
132
133
134
135
136
    {
        if (!self::shallFilterValue($cellValue)) {
            return $cellValue;
        }
        $cellValue = (string)$cellValue;
        return preg_replace('#^([\t\v=+*%/@-])#', '\'${1}', $cellValue);
    }

    /**
     * Removes control literals from the beginning of a cell value
     *
137
     * (e.g. `=+value` --> `value`)
138
     */
139
    protected static function removeControlLiterals(bool|int|float|string|null $cellValue): bool|int|float|string|null
140
    {
141
142
        if (!self::shallFilterValue($cellValue)) {
            return $cellValue;
143
        }
144
145
146
147
148
149
150
        $cellValue = (string)$cellValue;
        return preg_replace('#^([\t\v=+*%/@-]+)+#', '', $cellValue);
    }

    /**
     * Asserts scalar or null types for given cell value.
     */
151
    protected static function assertCellValueType(mixed $cellValue): void
152
153
154
155
156
157
158
159
160
161
162
163
    {
        // int, float, string, bool, null
        if ($cellValue === null || is_scalar($cellValue)) {
            return;
        }
        throw new \RuntimeException(
            sprintf('Unexpected type %s for cell value', gettype($cellValue)),
            1625562833
        );
    }

    /**
164
     * Whether cell value shall be filtered.
165
     *
166
167
     * This applies to everything that is not or cannot be represented
     * as boolean, integer or float.
168
     */
169
    protected static function shallFilterValue(bool|int|float|string|null $cellValue): bool
170
171
172
173
174
175
    {
        return $cellValue !== null
            && !is_bool($cellValue)
            && !is_numeric($cellValue)
            && !MathUtility::canBeInterpretedAsInteger($cellValue)
            && !MathUtility::canBeInterpretedAsFloat($cellValue);
176
    }
177
}