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

Writer::getNewline()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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