/
FileStream.php
58 lines (47 loc) · 1.15 KB
/
FileStream.php
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
<?php
declare(strict_types=1);
namespace SimonOndrej\UniversalParser\StreamReaders;
use SimonOndrej\UniversalParser\StreamReaderInterface;
class FileStream implements StreamReaderInterface
{
/**
* @var string
*/
private $fileName;
/**
* @var resource
*/
private $handle;
public function __construct(string $fileName)
{
$this->fileName = $fileName;
}
/**
* @return null|string Returns next line if present or null if next line does not exist.
*/
public function nextLine(): ?string
{
if (!$this->hasNextLine()) {
return null;
}
$nextLine = fgets($this->loadFileStream());
return \is_bool($nextLine) ? '' : $nextLine;
}
/**
* @return bool True when stream contains another line. Must not throw.
*/
public function hasNextLine(): bool
{
return !feof($this->loadFileStream());
}
/**
* @return bool|resource
*/
private function loadFileStream()
{
if ($this->handle === null) {
$this->handle = fopen($this->fileName, 'rb');
}
return $this->handle;
}
}