2 namespace Consolidation\OutputFormatters\Transformations;
4 use Consolidation\OutputFormatters\StructuredData\TableDataInterface;
5 use Consolidation\OutputFormatters\StructuredData\OriginalDataInterface;
7 class TableTransformation extends \ArrayObject implements TableDataInterface, OriginalDataInterface
13 const TABLE_LAYOUT = 'table';
14 const LIST_LAYOUT = 'list';
16 public function __construct($data, $fieldLabels, $rowLabels = [])
18 $this->headers = $fieldLabels;
19 $this->rowLabels = $rowLabels;
20 $rows = static::transformRows($data, $fieldLabels);
21 $this->layout = self::TABLE_LAYOUT;
22 parent::__construct($rows);
25 public function setLayout($layout)
27 $this->layout = $layout;
30 public function getLayout()
35 public function isList()
37 return $this->layout == self::LIST_LAYOUT;
40 protected static function transformRows($data, $fieldLabels)
43 foreach ($data as $rowid => $row) {
44 $rows[$rowid] = static::transformRow($row, $fieldLabels);
49 protected static function transformRow($row, $fieldLabels)
52 foreach ($fieldLabels as $key => $label) {
53 $result[$key] = array_key_exists($key, $row) ? $row[$key] : '';
58 public function getHeaders()
60 return $this->headers;
63 public function getHeader($key)
65 if (array_key_exists($key, $this->headers)) {
66 return $this->headers[$key];
71 public function getRowLabels()
73 return $this->rowLabels;
76 public function getRowLabel($rowid)
78 if (array_key_exists($rowid, $this->rowLabels)) {
79 return $this->rowLabels[$rowid];
84 public function getOriginalData()
86 return $this->getArrayCopy();
89 public function getTableData($includeRowKey = false)
91 $data = $this->getArrayCopy();
92 if ($this->isList()) {
93 $data = $this->convertTableToList();
96 $data = $this->getRowDataWithKey($data);
101 protected function convertTableToList()
104 foreach ($this as $row) {
105 foreach ($row as $key => $value) {
106 $result[$key][] = $value;
112 protected function getRowDataWithKey($data)
116 foreach ($data as $key => $row) {
117 array_unshift($row, $this->getHeader($key));
119 $result[$key] = $row;