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\Extractors\File; |
11
|
|
|
|
12
|
|
|
use fab2s\Bom\Bom; |
13
|
|
|
use fab2s\NodalFlow\NodalFlowException; |
14
|
|
|
use fab2s\YaEtl\Extractors\ExtractorAbstract; |
15
|
|
|
use fab2s\YaEtl\Traits\FileHandlerTrait; |
16
|
|
|
use fab2s\YaEtl\YaEtlException; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Class FileExtractorAbstract |
20
|
|
|
*/ |
21
|
|
|
abstract class FileExtractorAbstract extends ExtractorAbstract |
22
|
|
|
{ |
23
|
|
|
use FileHandlerTrait; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param resource|string $input |
27
|
|
|
* |
28
|
|
|
* @throws YaEtlException |
29
|
|
|
* @throws NodalFlowException |
30
|
|
|
*/ |
31
|
|
|
public function __construct($input) |
32
|
|
|
{ |
33
|
|
|
$this->initHandle($input, 'rb'); |
34
|
|
|
|
35
|
|
|
parent::__construct(); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param mixed $param |
40
|
|
|
* |
41
|
|
|
* @return bool |
42
|
|
|
*/ |
43
|
|
|
public function extract($param = null): bool |
44
|
|
|
{ |
45
|
|
|
return !feof($this->handle); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @return bool |
50
|
|
|
*/ |
51
|
|
|
protected function readBom(): bool |
52
|
|
|
{ |
53
|
|
|
if (false === ($bomCandidate = fread($this->handle, 4))) { |
54
|
|
|
return false; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/* @var string $bomCandidate */ |
58
|
|
|
if ($bom = Bom::extract($bomCandidate)) { |
59
|
|
|
$this->encoding = Bom::getBomEncoding($bom); |
60
|
|
|
|
61
|
|
|
return !fseek($this->handle, strlen($bom)); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return rewind($this->handle); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return string|null |
69
|
|
|
*/ |
70
|
|
|
protected function getNextNonEmptyLine(): ?string |
71
|
|
|
{ |
72
|
|
|
do { |
73
|
|
|
if (false === ($line = fgets($this->handle))) { |
74
|
|
|
return null; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
if ('' === ($line = trim($line))) { |
78
|
|
|
continue; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return $line; |
82
|
|
|
} while (!feof($this->handle)); |
83
|
|
|
|
84
|
|
|
return null; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
/** |
88
|
|
|
* @return string|null |
89
|
|
|
*/ |
90
|
|
|
protected function getNextNonEmptyChars(): ? string |
91
|
|
|
{ |
92
|
|
|
do { |
93
|
|
|
if (false === ($char = fread($this->handle, 1))) { |
94
|
|
|
return null; |
95
|
|
|
} |
96
|
|
|
|
97
|
|
|
if ('' === ($char = trim($char))) { |
98
|
|
|
continue; |
99
|
|
|
} |
100
|
|
|
|
101
|
|
|
return $char; |
102
|
|
|
} while (!feof($this->handle)); |
103
|
|
|
|
104
|
|
|
return null; |
105
|
|
|
} |
106
|
|
|
} |
107
|
|
|
|