Writer   A
last analyzed

Coupling/Cohesion

Components 1
Dependencies 3

Complexity

Total Complexity 23

Size/Duplication

Total Lines 237
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 23
lcom 1
cbo 3
dl 0
loc 237
ccs 59
cts 59
cp 1
rs 10
c 0
b 0
f 0

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getNewline() 0 4 1
A getFlushThreshold() 0 4 1
A addFormatter() 0 6 1
A addValidator() 0 6 1
A setNewline() 0 6 1
A formatRecord() 0 4 1
A validateRecord() 0 8 3
A consolidate() 0 20 4
A insertAll() 0 16 3
A insertOne() 0 11 2
B setFlushThreshold() 0 20 5
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.1.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 Traversable;
18
use TypeError;
19
20
/**
21
 * A class to insert records into a CSV Document
22
 *
23
 * @package League.csv
24
 * @since   4.0.0
25
 * @author  Ignace Nyamagana Butera <[email protected]>
26
 */
27
class Writer extends AbstractCsv
28
{
29
    /**
30
     * callable collection to format the record before insertion
31
     *
32
     * @var callable[]
33
     */
34
    protected $formatters = [];
35
36
    /**
37
     * callable collection to validate the record before insertion
38
     *
39
     * @var callable[]
40
     */
41
    protected $validators = [];
42
43
    /**
44
     * newline character
45
     *
46
     * @var string
47
     */
48
    protected $newline = "\n";
49
50
    /**
51
     * Insert records count for flushing
52
     *
53
     * @var int
54
     */
55
    protected $flush_counter = 0;
56
57
    /**
58
     * Buffer flush threshold
59
     *
60
     * @var int|null
61
     */
62
    protected $flush_threshold;
63
64
    /**
65
     * @inheritdoc
66
     */
67
    protected $stream_filter_mode = STREAM_FILTER_WRITE;
68
69
    /**
70
     * Returns the current newline sequence characters
71
     *
72
     * @return string
73
     */
74 2
    public function getNewline(): string
75
    {
76 2
        return $this->newline;
77
    }
78
79
    /**
80
     * Get the flush threshold
81
     *
82
     * @return int|null
83
     */
84 2
    public function getFlushThreshold()
85
    {
86 2
        return $this->flush_threshold;
87
    }
88
89
    /**
90
     * Adds multiple records to the CSV document
91
     *
92
     * a simple wrapper method around insertOne
93
     *
94
     * @param Traversable|array $records a multidimensional array or a Traversable object
95
     *
96
     * @return int
97
     */
98 6
    public function insertAll($records): int
99
    {
100 6
        if (!is_iterable($records)) {
101 2
            throw new TypeError(sprintf('%s() expects argument passed to be iterable, %s given', __METHOD__, gettype($records)));
102
        }
103
104 4
        $bytes = 0;
105 4
        foreach ($records as $record) {
106 4
            $bytes += $this->insertOne($record);
107
        }
108
109 4
        $this->flush_counter = 0;
110 4
        $this->document->fflush();
111
112 4
        return $bytes;
113
    }
114
115
    /**
116
     * Adds a single record to a CSV document
117
     *
118
     * @param string[] $record an array
119
     *
120
     * @throws CannotInsertRecord If the record can not be inserted
121
     *
122
     * @return int
123
     */
124 16
    public function insertOne(array $record): int
125
    {
126 16
        $record = array_reduce($this->formatters, [$this, 'formatRecord'], $record);
127 16
        $this->validateRecord($record);
128 14
        $bytes = $this->document->fputcsv($record, $this->delimiter, $this->enclosure, $this->escape);
129 14
        if (!$bytes) {
130 2
            throw CannotInsertRecord::triggerOnInsertion($record);
131
        }
132
133 12
        return $bytes + $this->consolidate();
134
    }
135
136
    /**
137
     * Format a record
138
     *
139
     * @param string[] $record
140
     * @param callable $formatter
141
     *
142
     * @return string[]
143
     */
144 2
    protected function formatRecord(array $record, callable $formatter): array
145
    {
146 2
        return $formatter($record);
147
    }
148
149
    /**
150
     * Validate a record
151
     *
152
     * @param string[] $record
153
     *
154
     * @throws CannotInsertRecord If the validation failed
155
     */
156 8
    protected function validateRecord(array $record)
157
    {
158 8
        foreach ($this->validators as $name => $validator) {
159 2
            if (true !== $validator($record)) {
160 2
                throw CannotInsertRecord::triggerOnValidation($name, $record);
161
            }
162
        }
163 6
    }
164
165
    /**
166
     * Apply post insertion actions
167
     *
168
     * @return int
169
     */
170 8
    protected function consolidate(): int
171
    {
172 8
        $bytes = 0;
173 8
        if ("\n" !== $this->newline) {
174 2
            $this->document->fseek(-1, SEEK_CUR);
175 2
            $bytes = $this->document->fwrite($this->newline, strlen($this->newline)) - 1;
176
        }
177
178 8
        if (null === $this->flush_threshold) {
179 6
            return $bytes;
180
        }
181
182 2
        ++$this->flush_counter;
183 2
        if (0 === $this->flush_counter % $this->flush_threshold) {
184 2
            $this->flush_counter = 0;
185 2
            $this->document->fflush();
186
        }
187
188 2
        return $bytes;
189
    }
190
191
    /**
192
     * Adds a record formatter
193
     *
194
     * @param callable $formatter
195
     *
196
     * @return static
197
     */
198 2
    public function addFormatter(callable $formatter): self
199
    {
200 2
        $this->formatters[] = $formatter;
201
202 2
        return $this;
203
    }
204
205
    /**
206
     * Adds a record validator
207
     *
208
     * @param callable $validator
209
     * @param string   $validator_name the validator name
210
     *
211
     * @return static
212
     */
213 2
    public function addValidator(callable $validator, string $validator_name): self
214
    {
215 2
        $this->validators[$validator_name] = $validator;
216
217 2
        return $this;
218
    }
219
220
    /**
221
     * Sets the newline sequence
222
     *
223
     * @param string $newline
224
     *
225
     * @return static
226
     */
227 2
    public function setNewline(string $newline): self
228
    {
229 2
        $this->newline = $newline;
230
231 2
        return $this;
232
    }
233
234
    /**
235
     * Set the flush threshold
236
     *
237
     * @param int|null $threshold
238
     *
239
     * @throws Exception if the threshold is a integer lesser than 1
240
     *
241
     * @return static
242
     */
243 6
    public function setFlushThreshold($threshold): self
244
    {
245 6
        if ($threshold === $this->flush_threshold) {
246 2
            return $this;
247
        }
248
249 6
        if (!is_nullable_int($threshold)) {
250 2
            throw new TypeError(sprintf(__METHOD__.'() expects 1 Argument to be null or an integer %s given', gettype($threshold)));
251
        }
252
253 4
        if (null !== $threshold && 1 >= $threshold) {
254 2
            throw new Exception(__METHOD__.'() expects 1 Argument to be null or a valid integer greater or equal to 1');
255
        }
256
257 4
        $this->flush_threshold = $threshold;
258 4
        $this->flush_counter = 0;
259 4
        $this->document->fflush();
260
261 4
        return $this;
262
    }
263
}
264