|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of YaEtl. |
|
5
|
|
|
* (c) Fabrice de Stefanis / https://github.com/fab2s/YaEtl |
|
6
|
|
|
* This source file is licensed under the MIT license which you will |
|
7
|
|
|
* find in the LICENSE file or at https://opensource.org/licenses/MIT |
|
8
|
|
|
*/ |
|
9
|
|
|
|
|
10
|
|
|
namespace fab2s\YaEtl\Loaders\File; |
|
11
|
|
|
|
|
12
|
|
|
use fab2s\NodalFlow\NodalFlowException; |
|
13
|
|
|
use fab2s\NodalFlow\YaEtlException; |
|
14
|
|
|
use fab2s\YaEtl\Traits\CsvHandlerTrait; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Class CsvLoader |
|
18
|
|
|
*/ |
|
19
|
|
|
class CsvLoader extends FileLoaderAbstract |
|
20
|
|
|
{ |
|
21
|
|
|
use CsvHandlerTrait; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @var bool |
|
25
|
|
|
*/ |
|
26
|
|
|
protected $isFirstLine = true; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* CsvLoader constructor. |
|
30
|
|
|
* |
|
31
|
|
|
* @param string $destination |
|
32
|
|
|
* @param string|null $delimiter |
|
33
|
|
|
* @param string|null $enclosure |
|
34
|
|
|
* @param string|null $escape |
|
35
|
|
|
* |
|
36
|
|
|
* @throws NodalFlowException |
|
37
|
|
|
* @throws YaEtlException |
|
38
|
|
|
*/ |
|
39
|
|
|
public function __construct($destination, $delimiter = null, $enclosure = null, $escape = null) |
|
40
|
|
|
{ |
|
41
|
|
|
parent::__construct($destination); |
|
42
|
|
|
$this->initCsvOptions($delimiter, $enclosure, $escape); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Execute this Node |
|
47
|
|
|
* |
|
48
|
|
|
* @param array $param |
|
49
|
|
|
*/ |
|
50
|
|
|
public function exec($param) |
|
51
|
|
|
{ |
|
52
|
|
|
// take care about header etc |
|
53
|
|
|
if ($this->isFirstLine) { |
|
54
|
|
|
if ($this->useSep) { |
|
55
|
|
|
fwrite($this->handle, "sep=$this->delimiter\n"); |
|
|
|
|
|
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
if ($this->useHeader) { |
|
59
|
|
|
if (!isset($this->header)) { |
|
60
|
|
|
$this->header = array_keys($param); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
$this->writeCsvLine($this->header); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
$this->isFirstLine = false; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
$this->writeCsvLine($param); |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* @param array $record |
|
74
|
|
|
* |
|
75
|
|
|
* @return bool|int |
|
76
|
|
|
*/ |
|
77
|
|
|
protected function writeCsvLine(array $record) |
|
78
|
|
|
{ |
|
79
|
|
|
return fputcsv($this->handle, $record, $this->delimiter, $this->enclosure, $this->escape); |
|
|
|
|
|
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|