Completed
Pull Request — master (#309)
by ignace nyamagana
02:32
created

Writer::addRFC4180CompliantRecord()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 3
rs 9.8666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * League.Csv (https://csv.thephpleague.com).
5
 *
6
 * @author  Ignace Nyamagana Butera <[email protected]>
7
 * @license https://github.com/thephpleague/csv/blob/master/LICENSE (MIT License)
8
 * @version 9.1.5
9
 * @link    https://github.com/thephpleague/csv
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
declare(strict_types=1);
16
17
namespace League\Csv;
18
19
use Traversable;
20
use TypeError;
21
use const SEEK_CUR;
22
use const STREAM_FILTER_WRITE;
23
use function array_reduce;
24
use function gettype;
25
use function implode;
26
use function is_iterable;
27
use function sprintf;
28
use function str_replace;
29
use function strlen;
30
31
/**
32
 * A class to insert records into a CSV Document.
33
 *
34
 * @package League.csv
35
 * @since   4.0.0
36
 * @author  Ignace Nyamagana Butera <[email protected]>
37
 */
38
class Writer extends AbstractCsv
39
{
40
    /**
41
     * callable collection to format the record before insertion.
42
     *
43
     * @var callable[]
44
     */
45
    protected $formatters = [];
46
47
    /**
48
     * callable collection to validate the record before insertion.
49
     *
50
     * @var callable[]
51
     */
52
    protected $validators = [];
53
54
    /**
55
     * newline character.
56
     *
57
     * @var string
58
     */
59
    protected $newline = "\n";
60
61
    /**
62
     * Insert records count for flushing.
63
     *
64
     * @var int
65
     */
66
    protected $flush_counter = 0;
67
68
    /**
69
     * Buffer flush threshold.
70
     *
71
     * @var int|null
72
     */
73
    protected $flush_threshold;
74
75
    /**
76
     * {@inheritdoc}
77
     */
78
    protected $stream_filter_mode = STREAM_FILTER_WRITE;
79
80
    /**
81
     * Regular expression used to detect if RFC4180 formatting is necessary.
82
     *
83
     * @var string
84
     */
85
    protected $rfc4180_regexp;
86
87
    /**
88
     * double enclosure for RFC4180 compliance.
89
     *
90
     * @var string
91
     */
92
    protected $rfc4180_enclosure;
93
94
    /**
95
     * {@inheritdoc}
96
     */
97 15
    protected function resetProperties()
98
    {
99 15
        parent::resetProperties();
100 15
        $characters = "\s|".preg_quote($this->delimiter, '/').'|'.preg_quote($this->enclosure, '/');
101 15
        $this->rfc4180_regexp = '/['.$characters.']/x';
102 15
        $this->rfc4180_enclosure = $this->enclosure.$this->enclosure;
103 15
    }
104
105
    /**
106
     * Returns the current newline sequence characters.
107
     */
108 3
    public function getNewline(): string
109
    {
110 3
        return $this->newline;
111
    }
112
113
    /**
114
     * Get the flush threshold.
115
     *
116
     * @return int|null
117
     */
118 3
    public function getFlushThreshold()
119
    {
120 3
        return $this->flush_threshold;
121
    }
122
123
    /**
124
     * Adds multiple records to the CSV document.
125
     *
126
     * @see Writer::insertOne
127
     *
128
     * @param Traversable|array $records
129
     */
130 9
    public function insertAll($records): int
131
    {
132 9
        if (!is_iterable($records)) {
133 3
            throw new TypeError(sprintf('%s() expects argument passed to be iterable, %s given', __METHOD__, gettype($records)));
134
        }
135
136 6
        $bytes = 0;
137 6
        foreach ($records as $record) {
138 6
            $bytes += $this->insertOne($record);
139
        }
140
141 6
        $this->flush_counter = 0;
142 6
        $this->document->fflush();
143
144 6
        return $bytes;
145
    }
146
147
    /**
148
     * Adds a single record to a CSV document.
149
     *
150
     * A record is an array that can contains scalar types values, NULL values
151
     * or objects implementing the __toString method.
152
     *
153
     * @throws CannotInsertRecord If the record can not be inserted
154
     */
155 54
    public function insertOne(array $record): int
156
    {
157 54
        $method = 'addRecord';
158 54
        if ('' === $this->escape && PHP_VERSION_ID < 70400) {
159 27
            $method = 'addRFC4180CompliantRecord';
160
        }
161
162 54
        $record = array_reduce($this->formatters, [$this, 'formatRecord'], $record);
163 54
        $this->validateRecord($record);
164 51
        $bytes = $this->$method($record);
165 51
        if (false !== $bytes && 0 !== $bytes) {
166 45
            return $bytes + $this->consolidate();
167
        }
168
169 6
        throw CannotInsertRecord::triggerOnInsertion($record);
170
    }
171
172
    /**
173
     * Adds a single record to a CSV Document using PHP algorithm.
174
     *
175
     * @see https://php.net/manual/en/function.fputcsv.php
176
     *
177
     * @return int|bool
178
     */
179 12
    protected function addRecord(array $record)
180
    {
181 12
        return $this->document->fputcsv($record, $this->delimiter, $this->enclosure, $this->escape);
182
    }
183
184
    /**
185
     * Adds a single record to a CSV Document using RFC4180 algorithm.
186
     *
187
     * @see https://php.net/manual/en/function.fputcsv.php
188
     * @see https://php.net/manual/en/function.fwrite.php
189
     * @see https://tools.ietf.org/html/rfc4180
190
     * @see http://edoceo.com/utilitas/csv-file-format
191
     *
192
     * String conversion is done without any check like fputcsv.
193
     *
194
     *     - Emits E_NOTICE on Array conversion (returns the 'Array' string)
195
     *     - Throws catchable fatal error on objects that can not be converted
196
     *     - Returns resource id without notice or error (returns 'Resource id #2')
197
     *     - Converts boolean true to '1', boolean false to the empty string
198
     *     - Converts null value to the empty string
199
     *
200
     * Fields must be delimited with enclosures if they contains :
201
     *
202
     *     - Embedded whitespaces
203
     *     - Embedded delimiters
204
     *     - Embedded line-breaks
205
     *     - Embedded enclosures.
206
     *
207
     * Embedded enclosures must be doubled.
208
     *
209
     * The LF character is added at the end of each record to mimic fputcsv behavior
210
     *
211
     * @return int|bool
212
     */
213 27
    protected function addRFC4180CompliantRecord(array $record)
214
    {
215 27
        foreach ($record as &$field) {
216 27
            $field = (string) $field;
217 27
            if (preg_match($this->rfc4180_regexp, $field)) {
218 27
                $field = $this->enclosure.str_replace($this->enclosure, $this->rfc4180_enclosure, $field).$this->enclosure;
219
            }
220
        }
221 27
        unset($field);
222
223 27
        return $this->document->fwrite(implode($this->delimiter, $record)."\n");
224
    }
225
226
    /**
227
     * Format a record.
228
     *
229
     * The returned array must contain
230
     *   - scalar types values,
231
     *   - NULL values,
232
     *   - or objects implementing the __toString() method.
233
     */
234 3
    protected function formatRecord(array $record, callable $formatter): array
235
    {
236 3
        return $formatter($record);
237
    }
238
239
    /**
240
     * Validate a record.
241
     *
242
     * @throws CannotInsertRecord If the validation failed
243
     */
244 12
    protected function validateRecord(array $record)
245
    {
246 12
        foreach ($this->validators as $name => $validator) {
247 3
            if (true !== $validator($record)) {
248 3
                throw CannotInsertRecord::triggerOnValidation($name, $record);
249
            }
250
        }
251 9
    }
252
253
    /**
254
     * Apply post insertion actions.
255
     */
256 12
    protected function consolidate(): int
257
    {
258 12
        $bytes = 0;
259 12
        if ("\n" !== $this->newline) {
260 3
            $this->document->fseek(-1, SEEK_CUR);
261 3
            $bytes = $this->document->fwrite($this->newline, strlen($this->newline)) - 1;
262
        }
263
264 12
        if (null === $this->flush_threshold) {
265 9
            return $bytes;
266
        }
267
268 3
        ++$this->flush_counter;
269 3
        if (0 === $this->flush_counter % $this->flush_threshold) {
270 3
            $this->flush_counter = 0;
271 3
            $this->document->fflush();
272
        }
273
274 3
        return $bytes;
275
    }
276
277
    /**
278
     * Adds a record formatter.
279
     */
280 3
    public function addFormatter(callable $formatter): self
281
    {
282 3
        $this->formatters[] = $formatter;
283
284 3
        return $this;
285
    }
286
287
    /**
288
     * Adds a record validator.
289
     */
290 3
    public function addValidator(callable $validator, string $validator_name): self
291
    {
292 3
        $this->validators[$validator_name] = $validator;
293
294 3
        return $this;
295
    }
296
297
    /**
298
     * Sets the newline sequence.
299
     */
300 3
    public function setNewline(string $newline): self
301
    {
302 3
        $this->newline = $newline;
303
304 3
        return $this;
305
    }
306
307
    /**
308
     * Set the flush threshold.
309
     *
310
     * @param int|null $threshold
311
     *
312
     * @throws Exception if the threshold is a integer lesser than 1
313
     */
314 12
    public function setFlushThreshold($threshold): self
315
    {
316 12
        if ($threshold === $this->flush_threshold) {
317 3
            return $this;
318
        }
319
320 12
        if (!is_nullable_int($threshold)) {
321 3
            throw new TypeError(sprintf(__METHOD__.'() expects 1 Argument to be null or an integer %s given', gettype($threshold)));
322
        }
323
324 9
        if (null !== $threshold && 1 > $threshold) {
325 3
            throw new Exception(__METHOD__.'() expects 1 Argument to be null or a valid integer greater or equal to 1');
326
        }
327
328 9
        $this->flush_threshold = $threshold;
329 9
        $this->flush_counter = 0;
330 9
        $this->document->fflush();
331
332 9
        return $this;
333
    }
334
}
335