-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathJsonStreamFile.php
More file actions
114 lines (93 loc) · 2.77 KB
/
JsonStreamFile.php
File metadata and controls
114 lines (93 loc) · 2.77 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
<?php
declare(strict_types=1);
/*
* This file is part of the CleverAge/ProcessBundle package.
*
* Copyright (c) Clever-Age
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CleverAge\ProcessBundle\Filesystem;
/**
* Wrapper around JSON files to read them in a stream.
*/
class JsonStreamFile implements FileStreamInterface, WritableFileInterface
{
protected \SplFileObject $file;
private readonly int $jsonFlags;
protected ?int $lineCount = null;
protected int $lineNumber = 1;
public function __construct(
string $filename,
string $mode = 'rb',
?array $splFileObjectFlags = null,
?array $jsonFlags = null,
) {
$this->file = new \SplFileObject($filename, $mode);
// Useful to skip empty trailing lines (doesn't work well on PHP 8, see readLine() code)
$this->file->setFlags(null !== $splFileObjectFlags
? array_sum($splFileObjectFlags)
: \SplFileObject::DROP_NEW_LINE | \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY
);
$this->jsonFlags = null !== $jsonFlags
? array_sum($jsonFlags)
: \JSON_THROW_ON_ERROR
;
}
/**
* Warning! This method will rewind the file to the beginning before and after counting the lines!
*/
public function getLineCount(): int
{
if (null === $this->lineCount) {
$this->rewind();
$line = 0;
while (!$this->isEndOfFile()) {
++$line;
$this->file->next();
}
$this->rewind();
$this->lineCount = $line;
}
return $this->lineCount;
}
public function getLineNumber(): int
{
return $this->lineNumber;
}
public function isEndOfFile(): bool
{
return $this->file->eof();
}
/**
* Return an array containing current data and moving the file pointer.
*/
public function readLine(?int $length = null): ?array
{
if ($this->isEndOfFile()) {
return null;
}
$rawLine = $this->file->fgets();
// Fix issue on PHP 8 with empty line at the end, even if SKIP_EMPTY is set
if ('' === $rawLine) {
return null;
}
++$this->lineNumber;
return json_decode($rawLine, true, 512, $this->jsonFlags);
}
public function writeLine(array $fields): int
{
$this->file->fwrite(json_encode($fields, $this->jsonFlags).\PHP_EOL);
++$this->lineNumber;
return $this->lineNumber;
}
/**
* Rewind data to array.
*/
public function rewind(): void
{
$this->file->rewind();
$this->lineNumber = 1;
}
}