-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCsv.php
More file actions
214 lines (191 loc) · 6 KB
/
Csv.php
File metadata and controls
214 lines (191 loc) · 6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
<?php
declare(strict_types=1);
/*
* This file is part of the csv-table-generator package.
*
* (c) E-commit <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Ecommit\CsvTableGenerator;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @phpstan-type Options array{
* header?: ?array<?string>,
* max_lines?: ?int,
* delimiter?: string,
* enclosure?: string,
* eol?: self::EOL_*,
* escape?: string,
* add_utf8_bom?: bool,
* }
* @phpstan-type ResolvedOptions array{
* header: ?array<?string>,
* max_lines: ?int,
* delimiter: string,
* enclosure: string,
* eol: self::EOL_*,
* escape: string,
* add_utf8_bom: bool,
* }
*/
class Csv
{
public const EOL_LF = 'LF';
public const EOL_CRLF = 'CR+LF';
/**
* @var resource|closed-resource|false|null
*/
protected mixed $handle = null;
protected string $pathDir;
protected string $filename;
protected string $currentPathname;
/**
* @var array<?string>|null
*/
protected ?array $header;
protected ?int $maxLines;
protected string $delimiter;
protected string $enclosure;
protected string $eol;
protected string $escape;
protected int $fileNumber = 0;
protected int $lines = 0;
protected int $totalLines = 0;
protected bool $addUtf8Bom = false;
/**
* Constructor.
*
* @param string $pathDir Path folder
* @param string $filename Filename (without path folder and extension)
* @param Options $options See README.md
*/
public function __construct(string $pathDir, string $filename, array $options = [])
{
$resolver = new OptionsResolver();
$resolver->setDefaults([
'header' => null,
'max_lines' => null,
'delimiter' => ',',
'enclosure' => '"',
'eol' => self::EOL_LF,
'escape' => '',
'add_utf8_bom' => false,
]);
$resolver->setAllowedTypes('header', ['null', 'array']);
$resolver->setAllowedTypes('max_lines', ['null', 'int']);
$resolver->setAllowedTypes('delimiter', 'string');
$resolver->setAllowedTypes('enclosure', 'string');
$resolver->setAllowedValues('eol', [self::EOL_LF, self::EOL_CRLF]);
$resolver->setAllowedTypes('escape', 'string');
$resolver->setAllowedTypes('add_utf8_bom', 'bool');
$this->configureOptions($resolver);
/** @var ResolvedOptions $options */
$options = $resolver->resolve($options);
// Test folder
$realPath = realpath($pathDir);
if (false === $realPath || !is_writable($realPath)) {
throw new \Exception(\sprintf('Folder %s does not exist or is not writable', $pathDir));
}
$this->pathDir = $realPath;
$this->filename = $filename;
$this->header = $options['header'];
if (empty($options['max_lines'])) {
$this->maxLines = null;
} else {
$this->maxLines = (int) $options['max_lines'];
}
$this->delimiter = $options['delimiter'];
$this->enclosure = $options['enclosure'];
$this->eol = $options['eol'];
$this->escape = $options['escape'];
$this->addUtf8Bom = $options['add_utf8_bom'];
$this->open();
}
/**
* Open CSV file.
*/
protected function open(): void
{
if (\is_resource($this->handle)) {
throw new \Exception(\sprintf('The file %s is already open', $this->filename));
}
++$this->fileNumber;
$this->lines = 0;
$filename = $this->filename;
if ($this->fileNumber > 1) {
$filename .= '-'.$this->fileNumber;
}
$this->currentPathname = $this->pathDir.'/'.$filename.'.csv';
$this->handle = fopen($this->currentPathname, 'wb'); // Binary is forced. EOL = "\n"
if (false === $this->handle) {
throw new \Exception(\sprintf('Error during the opening of the %s file', $this->filename));
}
if ($this->addUtf8Bom) {
if (false === fwrite($this->handle, \chr(0xEF).\chr(0xBB).\chr(0xBF))) {
throw new \Exception(\sprintf('Error during the UTF8-BOM writing in %s file', $this->filename));
}
}
if (null !== $this->header && \count($this->header) > 0) {
$this->write($this->header);
$this->lines = 0;
--$this->totalLines;
}
}
/**
* Close CSV file.
*/
public function close(): void
{
if (\is_resource($this->handle)) {
fclose($this->handle);
$this->handle = null;
}
}
/**
* Create new CSV file.
*/
protected function newFile(): void
{
$this->close();
$this->open();
}
/**
* Add line in CSV file.
*
* @param array<?scalar> $data
*/
public function write(array $data): void
{
// New file
if (null !== $this->maxLines && $this->maxLines == $this->lines) {
$this->newFile();
}
// Write
$eol = (self::EOL_CRLF === $this->eol) ? "\r\n" : "\n";
if (!\is_resource($this->handle)) {
throw new \Exception(\sprintf('Handle does not exist. File %s', $this->filename));
}
$result = fputcsv($this->handle, $data, $this->delimiter, $this->enclosure, $this->escape, $eol);
if (false === $result) {
throw new \Exception(\sprintf('Error during the writing in %s file', $this->filename));
}
++$this->lines;
++$this->totalLines;
}
public function getTotalLines(): int
{
return $this->totalLines;
}
/**
* Gets the path to the current file.
*/
public function getCurrentPathname(): ?string
{
return $this->currentPathname;
}
protected function configureOptions(OptionsResolver $resolver): void
{
}
}