Completed
Pull Request — master (#210)
by ignace nyamagana
12:18
created

Writer   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 219
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 21
lcom 1
cbo 3
dl 0
loc 219
ccs 49
cts 49
cp 1
rs 10
c 4
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getNewline() 0 4 1
A getFlushThreshold() 0 4 1
A insertAll() 0 15 4
A insertOne() 0 11 2
A formatRecord() 0 4 1
A validateRecord() 0 8 3
A consolidate() 0 15 4
A addFormatter() 0 6 1
A addValidator() 0 6 1
A setNewline() 0 6 1
A setFlushThreshold() 0 10 2
1
<?php
2
/**
3
* This file is part of the League.csv library
4
*
5
* @license http://opensource.org/licenses/MIT
6
* @link https://github.com/thephpleague/csv/
7
* @version 9.0.0
8
* @package League.csv
9
*
10
* For the full copyright and license information, please view the LICENSE
11
* file that was distributed with this source code.
12
*/
13
declare(strict_types=1);
14
15
namespace League\Csv;
16
17
use League\Csv\Exception\InsertionException;
18
use League\Csv\Exception\InvalidArgumentException;
19
use Traversable;
20
21
/**
22
 * A class to manage data insertion into a CSV
23
 *
24
 * @package League.csv
25
 * @since   4.0.0
26
 * @author  Ignace Nyamagana Butera <[email protected]>
27
 *
28
 */
29
class Writer extends AbstractCsv
30
{
31
    /**
32
     * @inheritdoc
33
     */
34
    protected $stream_filter_mode = STREAM_FILTER_WRITE;
35
36
    /**
37
     * callable collection to validate the record before insertion
38
     *
39
     * @var callable[]
40
     */
41
    protected $validators = [];
42
43
    /**
44
     * callable collection to format the record before insertion
45
     *
46
     * @var callable[]
47
     */
48
    protected $formatters = [];
49
50
    /**
51
     * Insert Rows count
52
     *
53
     * @var int
54
     */
55
    protected $insert_count = 0;
56
57
    /**
58
     * newline character
59
     *
60
     * @var string
61
     */
62
    protected $newline = "\n";
63
64
    /**
65
     * Buffer flush threshold
66
     *
67
     * @var int
68
     */
69
    protected $flush_threshold = 500;
70
71
    /**
72
     * Returns the current newline sequence characters
73
     *
74
     * @return string
75
     */
76 4
    public function getNewline(): string
77
    {
78 4
        return $this->newline;
79
    }
80
81
    /**
82
     * Get the flush threshold
83
     *
84
     * @return int|null
85
     */
86 2
    public function getFlushThreshold()
87
    {
88 2
        return $this->flush_threshold;
89
    }
90
91
    /**
92
     * Adds multiple lines to the CSV document
93
     *
94
     * a simple wrapper method around insertOne
95
     *
96
     * @param Traversable|array $rows a multidimensional array or a Traversable object
97
     *
98
     * @throws InvalidArgumentException If the given rows format is invalid
99
     *
100
     * @return int
101
     */
102 6
    public function insertAll($rows): int
103
    {
104 6
        if (!is_array($rows) && !$rows instanceof Traversable) {
105 2
            throw new InvalidArgumentException('the provided data must be an array OR a `Traversable` object');
106
        }
107
108 4
        $bytes = 0;
109 4
        foreach ($rows as $row) {
110 4
            $bytes += $this->insertOne($row);
111
        }
112
113 4
        $this->document->fflush();
114
115 4
        return $bytes;
116
    }
117
118
    /**
119
     * Adds a single line to a CSV document
120
     *
121
     * @param string[] $row an array
122
     *
123
     * @throws InsertionException If the row can not be inserted
124
     *
125
     * @return int
126
     */
127 32
    public function insertOne(array $row): int
128
    {
129 32
        $record = array_reduce($this->formatters, [$this, 'formatRecord'], $row);
130 32
        $this->validateRecord($record);
131 28
        $bytes = $this->document->fputcsv($record, $this->delimiter, $this->enclosure, $this->escape);
132 28
        if (!$bytes) {
133 2
            throw InsertionException::createFromCsv($record);
134
        }
135
136 26
        return $bytes + $this->consolidate();
137
    }
138
139
    /**
140
     * Format the given row
141
     *
142
     * @param string[] $record
143
     * @param callable $formatter
144
     *
145
     * @return string[]
146
     */
147 4
    protected function formatRecord(array $record, callable $formatter): array
148
    {
149 4
        return $formatter($record);
150
    }
151
152
    /**
153
     * Validate a row
154
     *
155
     * @param string[] $record
156
     *
157
     * @throws InsertionException If the validation failed
158
     */
159 32
    protected function validateRecord(array $record)
160
    {
161 32
        foreach ($this->validators as $name => $validator) {
162 8
            if (true !== ($validator)($record)) {
163 8
                throw InsertionException::createFromValidator($name, $record);
164
            }
165
        }
166 28
    }
167
168
    /**
169
     * Apply post insertion actions
170
     *
171
     * @return int
172
     */
173 26
    protected function consolidate(): int
174
    {
175 26
        $bytes = 0;
176 26
        if ("\n" !== $this->newline) {
177 4
            $this->document->fseek(-1, SEEK_CUR);
178 4
            $bytes = $this->document->fwrite($this->newline, strlen($this->newline)) - 1;
179
        }
180
181 26
        $this->insert_count++;
182 26
        if (null !== $this->flush_threshold && 0 === $this->insert_count % $this->flush_threshold) {
183 2
            $this->document->fflush();
184
        }
185
186 26
        return $bytes;
187
    }
188
189
    /**
190
     * add a formatter to the collection
191
     *
192
     * @param callable $formatter
193
     *
194
     * @return static
195
     */
196 4
    public function addFormatter(callable $formatter): self
197
    {
198 4
        $this->formatters[] = $formatter;
199
200 4
        return $this;
201
    }
202
203
    /**
204
     * add a Validator to the collection
205
     *
206
     * @param callable $validator
207
     * @param string   $name      the validator name
208
     *
209
     * @return static
210
     */
211 8
    public function addValidator(callable $validator, string $name): self
212
    {
213 8
        $this->validators[$name] = $validator;
214
215 8
        return $this;
216
    }
217
218
    /**
219
     * Sets the newline sequence characters
220
     *
221
     * @param string $newline
222
     *
223
     * @return static
224
     */
225 4
    public function setNewline(string $newline): self
226
    {
227 4
        $this->newline = (string) $newline;
228
229 4
        return $this;
230
    }
231
232
    /**
233
     * Set the automatic flush threshold on write
234
     *
235
     * @param int|null $val
236
     */
237 4
    public function setFlushThreshold($val): self
238
    {
239 4
        if (null !== $val) {
240 4
            $val = $this->filterInteger($val, 1, 'The flush threshold must be a valid positive integer or null');
241
        }
242
243 4
        $this->flush_threshold = $val;
244
245 4
        return $this;
246
    }
247
}
248