|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Maketok\DataMigration\Storage\Filesystem; |
|
4
|
|
|
|
|
5
|
|
|
class Resource implements ResourceInterface |
|
6
|
|
|
{ |
|
7
|
|
|
/** |
|
8
|
|
|
* @var \SplFileObject |
|
9
|
|
|
*/ |
|
10
|
|
|
private $descriptor; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* {@inheritdoc} |
|
14
|
|
|
*/ |
|
15
|
15 |
|
public function open($name, $mode) |
|
16
|
|
|
{ |
|
17
|
15 |
|
if (!file_exists(dirname($name))) { |
|
18
|
9 |
|
mkdir(dirname($name), 0755, true); |
|
19
|
9 |
|
} |
|
20
|
15 |
|
$this->descriptor = new \SplFileObject($name, $mode); |
|
21
|
15 |
|
$this->descriptor->setFlags(\SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE); |
|
22
|
15 |
|
return true; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* {@inheritdoc} |
|
27
|
|
|
*/ |
|
28
|
|
|
public function writeRow(array $row, $delimiter = ',', $enclosure = '"') |
|
29
|
|
|
{ |
|
30
|
10 |
|
$row = array_map(function ($var) { |
|
31
|
10 |
|
if (is_null($var)) { |
|
32
|
1 |
|
return '\N'; |
|
33
|
|
|
} |
|
34
|
10 |
|
return $var; |
|
35
|
10 |
|
}, $row); |
|
36
|
10 |
|
return $this->descriptor->fputcsv($row, $delimiter, $enclosure); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* {@inheritdoc} |
|
41
|
|
|
*/ |
|
42
|
16 |
|
public function close() |
|
43
|
|
|
{ |
|
44
|
16 |
|
$this->descriptor = null; |
|
45
|
16 |
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* {@inheritdoc} |
|
49
|
|
|
*/ |
|
50
|
6 |
|
public function readRow($delimiter = ',', $enclosure = '"', $escape = "\\") |
|
51
|
|
|
{ |
|
52
|
6 |
|
return $this->descriptor->fgetcsv($delimiter, $enclosure, $escape); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* {@inheritdoc} |
|
57
|
|
|
*/ |
|
58
|
1 |
|
public function rewind() |
|
59
|
|
|
{ |
|
60
|
1 |
|
$this->descriptor->rewind(); |
|
61
|
1 |
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* {@inheritdoc} |
|
65
|
|
|
*/ |
|
66
|
35 |
|
public function isActive() |
|
67
|
|
|
{ |
|
68
|
35 |
|
return isset($this->descriptor); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* {@inheritdoc} |
|
73
|
|
|
*/ |
|
74
|
11 |
|
public function cleanUp($filename) |
|
75
|
|
|
{ |
|
76
|
11 |
|
$dir = dirname($filename); |
|
77
|
11 |
|
unlink($filename); |
|
78
|
11 |
|
if ($this->isEmptyDir($dir)) { |
|
79
|
10 |
|
rmdir($dir); |
|
80
|
10 |
|
} |
|
81
|
11 |
|
} |
|
82
|
|
|
|
|
83
|
|
|
/** |
|
84
|
|
|
* @param $directory |
|
85
|
|
|
* @return bool|null |
|
86
|
|
|
*/ |
|
87
|
12 |
|
public function isEmptyDir($directory) |
|
88
|
|
|
{ |
|
89
|
12 |
|
if (!file_exists($directory) || !is_dir($directory) || !is_readable($directory)) { |
|
90
|
1 |
|
return null; |
|
91
|
|
|
} |
|
92
|
12 |
|
return count(scandir($directory)) == 2; |
|
93
|
|
|
} |
|
94
|
|
|
} |
|
95
|
|
|
|