CsvWriter   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 171
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 2
dl 0
loc 171
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 1
A setColumnHeaders() 0 7 1
A prepare() 0 8 2
A writeLine() 0 15 4
A writeItem() 0 12 3
A orderDataByColumnHeaders() 0 5 1
A finish() 0 4 1
1
<?php
2
3
namespace Jh\DataImportMagento\Writer;
4
5
use Ddeboer\DataImport\Exception\ReaderException;
6
use Ddeboer\DataImport\Writer\AbstractWriter;
7
8
/**
9
 * CSV Writer which provides more
10
 * options than the default
11
 *
12
 * Will also write headers and be strict with import
13
 * data. Expects data to be key => value pairs
14
 *
15
 * Class CsvWriter
16
 * @package Jh\DataImportMagento\Writer
17
 * @author Aydin Hassan <[email protected]>
18
 */
19
class CsvWriter extends AbstractWriter
20
{
21
    /**
22
     * CSV Delimiter
23
     *
24
     * @var string
25
     */
26
    protected $delimiter = ';';
27
28
    /**
29
     * CSV Enclosure.
30
     * fputcsv only encloses values
31
     * it deems need to be enclosed
32
     *
33
     * @var string
34
     */
35
    protected $enclosure = '"';
36
37
    /**
38
     * EOL because some people use
39
     * windows for batch processing???!
40
     *
41
     * @var string
42
     */
43
    protected $eol = "\n";
44
45
    /**
46
     * File pointer
47
     *
48
     * @var null|resource
49
     */
50
    protected $fp = null;
51
52
    /**
53
     * Column Headers
54
     *
55
     * @var null|array
56
     */
57
    protected $columnHeaders = null;
58
59
    /**
60
     * Count of headers
61
     *
62
     * @var int
63
     */
64
    protected $headersCount;
65
66
    /**
67
     * @var bool
68
     */
69
    private $encloseEmptyFields = false;
70
71
    /**
72
     *
73
     * @param \SplFileObject $file CSV file
74
     * @param string $mode See http://php.net/manual/en/function.fopen.php
75
     * @param string $delimiter The delimiter
76
     * @param string $enclosure The enclosure
77
     * @param string $eol The end of line string
78
     * @param bool $encloseEmptyFields Whether to enclose empty fields or not
79
     */
80
    public function __construct(
81
        \SplFileObject $file,
82
        $mode = 'w',
83
        $delimiter = ';',
84
        $enclosure = '"',
85
        $eol = "\n",
86
        $encloseEmptyFields = false
87
    ) {
88
        $this->fp                 = fopen($file->getPathname(), $mode);
89
        $this->delimiter          = $delimiter;
90
        $this->enclosure          = $enclosure;
91
        $this->eol                = $eol;
92
        $this->encloseEmptyFields = $encloseEmptyFields;
93
    }
94
95
    /**
96
     * Set column headers
97
     *
98
     * @param array $columnHeaders
99
     *
100
     * @return CsvReader
101
     */
102
    public function setColumnHeaders(array $columnHeaders)
103
    {
104
        $this->columnHeaders = $columnHeaders;
105
        $this->headersCount = count($columnHeaders);
106
107
        return $this;
108
    }
109
110
    /**
111
     * Write Column Header
112
     *
113
     * @return \Ddeboer\DataImport\Writer\WriterInterface
114
     */
115
    public function prepare()
116
    {
117
        if (null !== $this->columnHeaders) {
118
            $this->writeLine($this->columnHeaders);
119
        }
120
121
        return $this;
122
    }
123
124
    /**
125
     * TODO: Make stripping quotes/enclosure configurable
126
     * TODO: Make enclosing configurable
127
     * TODO: Use fputcsv when ALL_ENCLOSING not necessary
128
     *
129
     * Write a line, removing double quotes and then enclosing every
130
     * piece of data.
131
     *
132
     * @param array $data
133
     */
134
    public function writeLine(array $data)
135
    {
136
        $line = implode($this->delimiter, array_map(function ($string) {
137
            $string = str_replace('"', '', $string);
138
139
            if (!$this->encloseEmptyFields && empty($string) && $string !== '0') {
140
                //if the string is empty don't quote it
141
                return $string;
142
            }
143
144
            return sprintf('%s%s%s', $this->enclosure, $string, $this->enclosure);
145
        }, $data));
146
147
        fputs($this->fp, $line . $this->eol);
148
    }
149
150
    /**
151
     * TODO: Make ordering configurable
152
     *
153
     * {@inheritdoc}
154
     */
155
    public function writeItem(array $item)
156
    {
157
        if (null !== $this->columnHeaders) {
158
            if ($this->headersCount !== count($item)) {
159
                throw new ReaderException("Row contains a different amount of items to headers");
160
            }
161
162
            $item = $this->orderDataByColumnHeaders($item);
163
        }
164
165
        $this->writeLine($item);
166
    }
167
168
    /**
169
     * Order the data using the order of the Header rows
170
     * This assumes that each row has the keys which
171
     * correspond to the header
172
     *
173
     * @param array $data
174
     * @return array
175
     */
176
    public function orderDataByColumnHeaders(array $data)
177
    {
178
        $correctOrder = array_merge(array_flip($this->columnHeaders), $data);
179
        return array_values($correctOrder);
180
    }
181
182
    /**
183
     * {@inheritdoc}
184
     */
185
    public function finish()
186
    {
187
        fclose($this->fp);
188
    }
189
}
190