Completed
Pull Request — master (#81)
by Tim
04:12
created

Exporter::export()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 47
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 47
ccs 0
cts 32
cp 0
rs 8.5125
c 0
b 0
f 0
cc 6
eloc 25
nc 18
nop 2
crap 42
1
<?php
2
3
/**
4
 * TechDivision\Import\Adapter\Goodby\Exporter
5
 *
6
 * NOTICE OF LICENSE
7
 *
8
 * This source file is subject to the Open Software License (OSL 3.0)
9
 * that is available through the world-wide-web at this URL:
10
 * http://opensource.org/licenses/osl-3.0.php
11
 *
12
 * PHP version 5
13
 *
14
 * @author    Tim Wagner <[email protected]>
15
 * @copyright 2016 TechDivision GmbH <[email protected]>
16
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
17
 * @link      https://github.com/techdivision/import
18
 * @link      http://www.techdivision.com
19
 */
20
21
namespace TechDivision\Import\Adapter\Goodby;
22
23
use Goodby\CSV\Export\Protocol\ExporterInterface;
24
use Goodby\CSV\Export\Protocol\Exception\IOException;
25
use Goodby\CSV\Export\Standard\CsvFileObject;
26
use Goodby\CSV\Export\Standard\ExporterConfig;
27
use Goodby\CSV\Export\Standard\Exception\StrictViolationException;
28
29
/**
30
 * Custom exporter implementation which resets row consistency on every import.
31
 *
32
 * @author    Tim Wagner <[email protected]>
33
 * @copyright 2016 TechDivision GmbH <[email protected]>
34
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
35
 * @link      https://github.com/techdivision/import
36
 * @link      http://www.techdivision.com
37
 */
38
class Exporter implements ExporterInterface
39
{
40
41
    /**
42
     * The exporter configuration.
43
     *
44
     * @var \Goodby\CSV\Export\Standard\ExporterConfig
45
     */
46
    private $config;
47
48
    /**
49
     * The number of rows found in the header.
50
     *
51
     * @var int
52
     */
53
    private $rowConsistency = null;
54
55
    /**
56
     * Query whether or not strict mode is activated or not.
57
     *
58
     * @var boolean
59
     */
60
    private $strict = true;
61
62
    /**
63
     * Initialize the instance with the passed configuration.
64
     *
65
     * @param \Goodby\CSV\Export\Standard\ExporterConfig $config The exporter configuration
66
     */
67
    public function __construct(ExporterConfig $config)
68
    {
69
        $this->config = $config;
70
    }
71
72
    /**
73
     * Disable strict mode.
74
     *
75
     * @return void
76
     */
77
    public function unstrict()
78
    {
79
        $this->strict = false;
80
    }
81
82
    /**
83
     * Query whether or not strict mode has been activated.
84
     *
85
     * @return boolean TRUE if the strict mode has NOT been activated, else FALSE
86
     */
87
    private function isNotStrict()
88
    {
89
        return $this->strict === false;
90
    }
91
92
    /**
93
     * Export data as CSV file.
94
     *
95
     * @param string $filename The filename to export to
96
     * @param array  $rows     The rows to export
97
     *
98
     * @return void
99
     * @throws \Goodby\CSV\Export\Protocol\Exception\IOException
100
     */
101
    public function export($filename, $rows)
102
    {
103
104
        // reset the exporter
105
        $this->reset();
106
107
        // initialize the configuration
108
        $delimiter     = $this->config->getDelimiter();
109
        $enclosure     = $this->config->getEnclosure();
110
        $enclosure     = empty($enclosure) ? "\0" : $enclosure;
111
        $newline       = $this->config->getNewline();
112
        $fromCharset   = $this->config->getFromCharset();
113
        $toCharset     = $this->config->getToCharset();
114
        $fileMode      = $this->config->getFileMode();
115
        $columnHeaders = $this->config->getColumnHeaders();
116
117
        try {
118
            $csv = new CsvFileObject($filename, $fileMode);
119
        } catch (\Exception $e) {
120
            throw new IOException($e->getMessage(), null, $e);
121
        }
122
123
        // set the new line char
124
        $csv->setNewline($newline);
125
126
        // query whether we've to convert the charset
127
        if ($toCharset) {
128
            $csv->setCsvFilter(function($line) use ($toCharset, $fromCharset) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
129
                return mb_convert_encoding($line, $toCharset, $fromCharset);
130
            });
131
        }
132
133
        // export the header
134
        if (count($columnHeaders) > 0) {
135
            $this->checkRowConsistency($columnHeaders);
136
            $csv->fputcsv($columnHeaders, $delimiter, $enclosure);
137
        }
138
139
        // export the rows
140
        foreach ($rows as $row) {
141
            $this->checkRowConsistency($row);
142
            $csv->fputcsv($row, $delimiter, $enclosure);
143
        }
144
145
        // flush the CSV file
146
        $csv->fflush();
147
    }
148
149
    /**
150
     * Reset the interpreter.
151
     *
152
     * @return void
153
     */
154
    public function reset()
155
    {
156
        $this->rowConsistency = null;
157
    }
158
159
    /**
160
     * Check if the column count is consistent with comparing other rows.
161
     *
162
     * @param array $row The row to check consistency for
163
     *
164
     * @return void
165
     * @throws \Goodby\CSV\Export\Standard\Exception\StrictViolationException Is thrown, if row consistency check fails
166
     */
167 View Code Duplication
    private function checkRowConsistency(array $row)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
168
    {
169
170
        // query whether or not strict mode is enabled
171
        if ($this->isNotStrict()) {
172
            return;
173
        }
174
175
        // count the number of columns
176
        $current = count($row);
177
178
        // if the row consistency has not been set, set it
179
        if ($this->rowConsistency === null) {
180
            $this->rowConsistency = $current;
181
        }
182
183
        // check row consistency
184
        if ($current !== $this->rowConsistency) {
185
            throw new StrictViolationException(sprintf('Column size should be %u, but %u columns given', $this->rowConsistency, $current));
186
        }
187
188
        // set the new row consistency
189
        $this->rowConsistency = $current;
190
    }
191
}
192