IteratorFileCsv::makeCurrent()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
nc 4
nop 0
dl 0
loc 32
ccs 17
cts 17
cp 1
crap 5
rs 9.0968
c 0
b 0
f 0
1
<?php
2
3
namespace NwLaravel\Iterators;
4
5
/**
6
 * Library Result Csv
7
 */
8
class IteratorFileCsv extends AbstractIteratorFile implements IteratorInterface
9
{
10
    /**
11
     * @var array|null
12
     */
13
    protected $headers;
14
15
    /**
16
     * @var string
17
     */
18
    protected $delimiter;
19
20
    /**
21
     * @var string
22
     */
23
    protected $enclosure;
24
25
    /**
26
     * @var string|null
27
     */
28
    protected $escape;
29
30
    /**
31
     * @var array
32
     */
33
    protected $defaults = array();
34
35
    /**
36
     * @var array
37
     */
38
    protected $replace = array();
39
40
    const DELIMITER_DEFAULT = ';';
41
    const ENCLOSURE_DEFAULT = '"';
42
    const ESCAPE_DEFAULT = '\\';
43
44
   /**
45
     * Abre o arquivo para leitura e define a variaveis
46
     *
47
     * @param string $fileName  File Name
48
     * @param string $headers   Headers [optional]
49
     * @param string $delimiter Separator Fields [optional]
50
     * @param string $enclosure Enclosure Fields [optional]
51
     * @param string $escape    String de Escape [optional]
52
     *
53
     * @throws \RuntimeException
54
     */
55 4
    public function __construct(
56
        $fileName,
57
        array $headers = array(),
58
        $delimiter = null,
59
        $enclosure = null,
60
        $escape = null
61
    ) {
62 4
        parent::__construct($fileName);
63
64 4
        $this->setHeaders($headers);
65 4
        $this->delimiter = (string) !is_null($delimiter) ? $delimiter : self::DELIMITER_DEFAULT;
66 4
        $this->enclosure = $enclosure ?: self::ENCLOSURE_DEFAULT;
67 4
        $this->escape    = $escape ?: self::ESCAPE_DEFAULT;
68 4
    }
69
70
    /**
71
     * Line to array
72
     *
73
     * @return array|null
74
     */
75 2
    private function rowArray()
76
    {
77 2
        $row = fgetcsv($this->fileHandle, null, $this->delimiter, $this->enclosure, $this->escape);
78 2
        if (is_array($row)) {
79
            $row = array_map(function ($value) {
80 2
                $value = trim($value);
81 2
                if (mb_detect_encoding($value, 'UTF-8', true) != 'UTF-8') {
82 1
                    $value = utf8_encode($value);
83 1
                }
84 2
                return $value;
85 2
            }, $row);
86 2
        }
87
88 2
        return $row;
89
    }
90
91
    /**
92
     * Make Row Current
93
     *
94
     * @return array|bool
95
     */
96 1
    public function makeCurrent()
97
    {
98 1
        $row = $this->rowArray();
99 1
        if (!is_array($row)) {
100 1
            return false;
101
        }
102
103
        $validateRow = array_filter($row, function ($value) {
104 1
            return ($value === '0') ? true : !empty($value);
105 1
        });
106
107 1
        if (!count($validateRow)) {
108 1
            return (array) $validateRow; // Vazio
109
        }
110
111 1
        $headers = $this->getHeaders();
112 1
        $count_headers = count($headers);
113
114
        // Falta valores, Existe mais Headers
115 1
        if ($count_headers > count($row)) {
116 1
            $row = array_pad($row, $count_headers, "");
117
118 1
        } else {
119
            // Sobrando valores, Existe mais valores
120 1
            $row = array_slice($row, 0, $count_headers);
121
        }
122
123 1
        $row = array_combine($headers, $row);
124 1
        $row = array_merge($this->defaults, $row, $this->replace);
125
126 1
        return $row;
127
    }
128
129
    /**
130
     * Conta as linhas como csv
131
     *
132
     * @return integer
133
     */
134 1
    public function count()
135
    {
136 1
        if (is_null($this->count)) {
137 1
            $this->count = 0;
138 1
            $data = (array) stream_get_meta_data($this->fileHandle);
139 1
            if (isset($data['uri'])) {
140 1
                $cmd = 'awk -v RS=\'"\' \'NR % 2 == 0 { gsub(/\n/, "") } { printf("%s%s", $0, RT) }\' ' . $data['uri'] . ' | wc -l';
141 1
                $this->count = intval(@exec($cmd));
142 1
            }
143 1
        }
144
145 1
        return $this->count;
146
    }
147
148
    /**
149
     * Rewind na segunda linha
150
     *
151
     * @see FileIterator::rewind()
152
     * @return void
153
     */
154 1
    public function rewind()
155
    {
156 1
        parent::rewind();
157 1
        $this->key = 1;
158 1
        $this->next(); // Pular Cabeçalho
159 1
    }
160
161
    /**
162
     * Retorna o headers tendo como chave a posicao das colunas da planilha
163
     *
164
     * @return array
165
     */
166 2
    public function getHeaders()
167
    {
168 2
        if (is_null($this->headers)) {
169 2
            $tell = ftell($this->fileHandle);
170 2
            fseek($this->fileHandle, 0);
171 2
            $row = $this->rowArray();
172 2
            $headers = array();
173
174 2
            if (is_array($row)) {
175 2
                $headers = array_map(function ($title) {
176 2
                    return strtolower(str_slug($title, '_'));
0 ignored issues
show
Deprecated Code introduced by
The function str_slug() has been deprecated with message: Str::slug() should be used directly instead. Will be removed in Laravel 6.0.

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
177 2
                }, $row);
178 2
            }
179
180 2
            fseek($this->fileHandle, $tell);
181 2
            $this->headers = $headers;
182 2
        }
183
184 2
        return $this->headers;
185
    }
186
187
    /**
188
     * Set Headers
189
     *
190
     * @param array $headers Headers
191
     *
192
     * @return IteratorFileCsv
193
     */
194 4
    public function setHeaders(array $headers)
195
    {
196 4
        $this->headers = count($headers) ? $headers : null;
197 4
        return $this;
198
    }
199
200
    /**
201
     * Set Fields Defaults
202
     *
203
     * @param array $defaults Defaults
204
     *
205
     * @return void
206
     */
207 1
    public function setDefaults(array $defaults)
208
    {
209 1
        $this->defaults = $defaults;
210 1
        return $this;
211
    }
212
213
    /**
214
     * Set Fields Replace
215
     *
216
     * @param array $replace Replaces
217
     *
218
     * @return void
219
     */
220 1
    public function setReplace(array $replace)
221
    {
222 1
        $this->replace = $replace;
223 1
        return $this;
224
    }
225
}
226