-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathJsonStreamFile.php
More file actions
121 lines (104 loc) · 2.56 KB
/
Copy pathJsonStreamFile.php
File metadata and controls
121 lines (104 loc) · 2.56 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
115
116
117
118
119
120
121
<?php declare(strict_types=1);
/*
* This file is part of the CleverAge/ProcessBundle package.
*
* Copyright (C) 2017-2021 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
{
/** @var \SplFileObject */
protected $file;
/** @var int */
protected $lineCount;
/** @var int */
protected $lineNumber = 1;
/**
* JsonStreamFile constructor.
*
* @param string $filename
* @param string $mode
*/
public function __construct(string $filename, $mode = 'rb')
{
$this->file = new \SplFileObject($filename, $mode);
// Useful to skip empty trailing lines
$this->file->setFlags(\SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY);
}
/**
* Warning! This method will rewind the file to the beginning before and after counting the lines!
*
* @throws \RuntimeException
*
* @return int
*/
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;
}
/**
* {@inheritDoc}
*/
public function getLineNumber(): int
{
return $this->lineNumber;
}
/**
* @return bool
*/
public function isEndOfFile(): bool
{
return $this->file->eof();
}
/**
* Return an array containing current data and moving the file pointer
*
* @param null $length
*
* @return array|null
*/
public function readLine($length = null): ?array
{
if ($this->isEndOfFile()) {
return null;
}
$rawLine = $this->file->fgets();
$this->lineNumber++;
return json_decode($rawLine, true);
}
/**
* @param array $item
*
* @return int
*/
public function writeLine(array $item): int
{
$this->file->fwrite(json_encode($item).PHP_EOL);
$this->lineNumber++;
return $this->lineNumber;
}
/**
* Rewind data to array
*/
public function rewind(): void
{
$this->file->rewind();
$this->lineNumber = 1;
}
}