2 namespace Consolidation\OutputFormatters\StructuredData;
4 use Consolidation\OutputFormatters\Options\FormatterOptions;
6 use Consolidation\OutputFormatters\Formatters\FormatterAwareInterface;
7 use Consolidation\OutputFormatters\Formatters\FormatterAwareTrait;
10 * Create a formatter to add commas to numeric data.
22 * This formatter may also be re-used for other purposes where right-justified
23 * data is desired by simply making a subclass. See method comments below.
27 * return (new RowsOfFields($data))->addRenderer(
28 * new NumericCellRenderer($data, ['value'])
32 class NumericCellRenderer implements RenderCellInterface, FormatterAwareInterface
34 use FormatterAwareTrait;
37 protected $renderedColumns;
38 protected $widths = [];
41 * NumericCellRenderer constructor
43 public function __construct($data, $renderedColumns)
46 $this->renderedColumns = $renderedColumns;
52 public function renderCell($key, $cellData, FormatterOptions $options, $rowData)
54 if (!$this->isRenderedFormat($options) || !$this->isRenderedColumn($key)) {
57 if ($this->isRenderedData($cellData)) {
58 $cellData = $this->formatCellData($cellData);
60 return $this->justifyCellData($key, $cellData);
64 * Right-justify the cell data.
66 protected function justifyCellData($key, $cellData)
68 return str_pad($cellData, $this->columnWidth($key), " ", STR_PAD_LEFT);
72 * Determine if this format is to be formatted.
74 protected function isRenderedFormat(FormatterOptions $options)
76 return $this->isHumanReadable();
80 * Determine if this is a column that should be formatted.
82 protected function isRenderedColumn($key)
84 return array_key_exists($key, $this->renderedColumns);
88 * Ignore cell data that should not be formatted.
90 protected function isRenderedData($cellData)
92 return is_numeric($cellData);
96 * Format the cell data.
98 protected function formatCellData($cellData)
100 return number_format($this->convertCellDataToString($cellData));
104 * This formatter only works with columns whose columns are strings.
105 * To use this formatter for another purpose, override this method
106 * to ensure that the cell data is a string before it is formatted.
108 protected function convertCellDataToString($cellData)
114 * Get the cached column width for the provided key.
116 protected function columnWidth($key)
118 if (!isset($this->widths[$key])) {
119 $this->widths[$key] = $this->calculateColumnWidth($key);
121 return $this->widths[$key];
125 * Using the cached table data, calculate the largest width
126 * for the data in the table for use when right-justifying.
128 protected function calculateColumnWidth($key)
130 $width = isset($this->renderedColumns[$key]) ? $this->renderedColumns[$key] : 0;
131 foreach ($this->data as $row) {
132 $data = $this->formatCellData($row[$key]);
133 $width = max(strlen($data), $width);