CSVWriter::write()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 14
ccs 6
cts 6
cp 1
crap 2
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * neuralyzer : Data Anonymization Library and CLI Tool
7
 *
8
 * PHP Version 7.2
9
 *
10
 * @author Emmanuel Dyan
11
 * @author Rémi Sauvat
12
 *
13
 * @copyright 2020 Emmanuel Dyan
14
 *
15
 * @package edyan/neuralyzer
16
 *
17
 * @license GNU General Public License v2.0
18
 *
19
 * @link https://github.com/edyan/neuralyzer
20
 */
21
22
namespace Edyan\Neuralyzer\Utils;
23
24
/**
25
 * A few generic methods to help interacting with DB
26
 */
27
class CSVWriter extends \SplFileObject
28 12
{
29
    /**
30 12
     * Create a temporary file
31 12
     */
32
    public function __construct()
33
    {
34
        parent::__construct(tempnam(sys_get_temp_dir(), 'neuralyzer'), 'w');
35
    }
36
37
    /**
38 10
     * Write a CSV line either by PHP standard or manually when no $enclosure
39
     *
40 10
     * @param  array  $fields
41 10
     */
42 10
    public function write(array $fields): int
43 10
    {
44 1
        $options = $this->getCsvControl();
45
        $delimiter = $options[0];
46
        $enclosure = $options[1];
47
        if (! empty($enclosure)) {
48 9
            return $this->fputcsv($fields, $delimiter, $enclosure);
49 9
        }
50
51 9
        $fields = array_map(static function ($field) use ($delimiter) {
52
            return str_replace([$delimiter, PHP_EOL], ['', ''], (string) $field);
53
        }, $fields);
54
55
        return $this->fwrite(implode($delimiter, $fields) . PHP_EOL);
56
    }
57
}
58