@@ -12,6 +12,9 @@ class StreamParseSql
12
12
13
13
const DEFAULT_CHUNK_SIZE = 4096 ;
14
14
15
+ /** @var callable[] */
16
+ private $ _onProgress = [];
17
+
15
18
/** @var string */
16
19
protected $ _filePath = '' ;
17
20
@@ -77,15 +80,18 @@ public function parse(): Generator
77
80
$ tokenizer = new Tokenizer ($ this ->getDelimiter ());
78
81
$ tokens = [];
79
82
$ filePath = $ this ->getFilePath ();
83
+ $ size = filesize ($ filePath );
80
84
$ fh = fopen ($ filePath , 'r ' );
81
85
if (!is_resource ($ fh )) {
82
86
throw new Exception \FileReadException ($ filePath );
83
87
}
84
88
if (!flock ($ fh , LOCK_SH )) {
85
89
throw new Exception \FileLockException ($ filePath );
86
90
}
91
+ $ pos = 0 ;
87
92
while (!feof ($ fh )) {
88
93
$ line = fread ($ fh , $ this ->_chunkSize );
94
+ $ pos += min (strlen ($ line ), $ this ->_chunkSize );
89
95
foreach ($ tokenizer ->append ($ line , feof ($ fh )) as $ token ) {
90
96
switch ($ token ->type ) {
91
97
case 'COMMENT_SINGLE ' :
@@ -101,11 +107,19 @@ public function parse(): Generator
101
107
break ;
102
108
}
103
109
}
110
+ foreach ($ this ->_onProgress as $ callback ) {
111
+ $ callback ($ pos , $ size );
112
+ }
104
113
}
105
114
flock ($ fh , LOCK_UN );
106
115
fclose ($ fh );
107
116
if (count ($ tokens ) > 0 ) {
108
117
yield Token::Assemble (...$ tokens );
109
118
}
110
119
}
120
+
121
+ public function onProgress (callable $ callback ): void
122
+ {
123
+ $ this ->_onProgress [] = $ callback ;
124
+ }
111
125
}
0 commit comments