Completed
Pull Request — master (#210)
by ignace nyamagana
02:31
created

Writer::validateRecord()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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