trait FormatTrait
Writes rows of data as a table, JSON or YAML.
Hierarchy
- trait \Drupal\devel\Command\FormatTrait
File
-
src/
Command/ FormatTrait.php, line 14
Namespace
Drupal\devel\CommandView source
trait FormatTrait {
/**
* Writes rows in the requested format.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* The output.
* @param array<int, array<string, mixed>> $rows
* The rows, each keyed by field name.
* @param array<string, string> $headers
* The table headers, keyed by field name.
* @param string $format
* One of table, json or yaml.
*/
protected function writeRows(OutputInterface $output, array $rows, array $headers, string $format) : void {
switch ($format) {
case 'json':
$output->writeln(json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR), OutputInterface::OUTPUT_RAW);
break;
case 'yaml':
$output->write(Yaml::encode($rows), FALSE, OutputInterface::OUTPUT_RAW);
break;
case 'table':
(new Table($output))->setHeaders(array_values($headers))
->setRows(array_map(static fn(array $row): array => array_map(strval(...), array_values($row)), $rows))
->render();
break;
default:
throw new \InvalidArgumentException(sprintf('Unknown format %s. Use table, json or yaml.', $format));
}
}
}
Members
| Title Sort descending | Modifiers | Object type | Summary |
|---|---|---|---|
| FormatTrait::writeRows | protected | function | Writes rows in the requested format. |