2 namespace Consolidation\OutputFormatters\Transformations;
4 use Consolidation\OutputFormatters\StructuredData\TableDataInterface;
5 use Consolidation\OutputFormatters\StructuredData\OriginalDataInterface;
6 use Consolidation\OutputFormatters\StructuredData\MetadataHolderInterface;
8 class TableTransformation extends \ArrayObject implements TableDataInterface, OriginalDataInterface
13 /** @var MetadataHolderInterface */
14 protected $originalData;
16 const TABLE_LAYOUT = 'table';
17 const LIST_LAYOUT = 'list';
19 public function __construct($data, $fieldLabels, $rowLabels = [])
21 $this->headers = $fieldLabels;
22 $this->rowLabels = $rowLabels;
23 $rows = static::transformRows($data, $fieldLabels);
24 $this->layout = self::TABLE_LAYOUT;
25 parent::__construct($rows);
28 public function setLayout($layout)
30 $this->layout = $layout;
33 public function getLayout()
38 public function isList()
40 return $this->layout == self::LIST_LAYOUT;
43 protected static function transformRows($data, $fieldLabels)
46 foreach ($data as $rowid => $row) {
47 $rows[$rowid] = static::transformRow($row, $fieldLabels);
52 protected static function transformRow($row, $fieldLabels)
55 foreach ($fieldLabels as $key => $label) {
56 $result[$key] = array_key_exists($key, $row) ? $row[$key] : '';
61 public function getHeaders()
63 return $this->headers;
66 public function getHeader($key)
68 if (array_key_exists($key, $this->headers)) {
69 return $this->headers[$key];
74 public function getRowLabels()
76 return $this->rowLabels;
79 public function getRowLabel($rowid)
81 if (array_key_exists($rowid, $this->rowLabels)) {
82 return $this->rowLabels[$rowid];
87 public function getOriginalData()
89 if (isset($this->originalData)) {
90 return $this->originalData->reconstruct($this->getArrayCopy(), $this->originalData->getMetadata());
92 return $this->getArrayCopy();
95 public function setOriginalData(MetadataHolderInterface $data)
97 $this->originalData = $data;
100 public function getTableData($includeRowKey = false)
102 $data = $this->getArrayCopy();
103 if ($this->isList()) {
104 $data = $this->convertTableToList();
106 if ($includeRowKey) {
107 $data = $this->getRowDataWithKey($data);
112 protected function convertTableToList()
115 foreach ($this as $row) {
116 foreach ($row as $key => $value) {
117 $result[$key][] = $value;
123 protected function getRowDataWithKey($data)
127 foreach ($data as $key => $row) {
128 array_unshift($row, $this->getHeader($key));
130 $result[$key] = $row;