FormatTrait.php

Namespace

Drupal\devel\Command

File

src/Command/FormatTrait.php

View source
<?php

declare (strict_types=1);
namespace Drupal\devel\Command;

use Drupal\Component\Serialization\Yaml;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Writes rows of data as a table, JSON or YAML.
 */
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));
    }
  }

}

Traits

Title Deprecated Summary
FormatTrait Writes rows of data as a table, JSON or YAML.