Skip to content

Commit b146b9f

Browse files
committed
feat: add streaming output helps to command base class
Signed-off-by: Robin Appelman <robin@icewind.nl>
1 parent 7c478db commit b146b9f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

core/Command/Base.php

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,58 @@ protected function writeTableInOutputFormat(InputInterface $input, OutputInterfa
104104
}
105105
}
106106

107+
protected function writeStreamingTableInOutputFormat(InputInterface $input, OutputInterface $output, \Iterator $items, int $tableGroupSize): void {
108+
switch ($input->getOption('output')) {
109+
case self::OUTPUT_FORMAT_JSON:
110+
case self::OUTPUT_FORMAT_JSON_PRETTY:
111+
$this->writeStreamingJsonArray($input, $output, $items);
112+
break;
113+
default:
114+
foreach ($this->chunkIterator($items, $tableGroupSize) as $chunk) {
115+
$this->writeTableInOutputFormat($input, $output, $chunk);
116+
}
117+
break;
118+
}
119+
}
120+
121+
protected function writeStreamingJsonArray(InputInterface $input, OutputInterface $output, \Iterator $items): void {
122+
$first = true;
123+
$outputType = $input->getOption('output');
124+
125+
$output->writeln('[');
126+
foreach ($items as $item) {
127+
if (!$first) {
128+
$output->writeln(',');
129+
}
130+
if ($outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
131+
$output->write(json_encode($item, JSON_PRETTY_PRINT));
132+
} else {
133+
$output->write(json_encode($item));
134+
}
135+
$first = false;
136+
}
137+
$output->writeln("\n]");
138+
}
139+
140+
public function chunkIterator(\Iterator $iterator, int $count): \Iterator {
141+
$chunk = [];
142+
143+
for ($i = 0; $iterator->valid(); $i++) {
144+
$chunk[] = $iterator->current();
145+
$iterator->next();
146+
if (count($chunk) == $count) {
147+
// Got a full chunk, yield and start a new one
148+
yield $chunk;
149+
$chunk = [];
150+
}
151+
}
152+
153+
if (count($chunk)) {
154+
// Yield the last chunk even if incomplete
155+
yield $chunk;
156+
}
157+
}
158+
107159

108160
/**
109161
* @param mixed $item

0 commit comments

Comments
 (0)