Debian Codegraph @

classes/TextTable.php

raw symbols SCIP
1 <?php
2
3 /**
4 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
5 * Copyright (C) 2024 Aleksey Andreev (liuch)
6 *
7 * Available at:
8 * https://github.com/liuch/dmarc-srg
9 *
10 * This program is free software: you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the Free
12 * Software Foundation, either version 3 of the License.
13 *
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 * more details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * =========================
23 *
24 * This file contains the class TextTable
25 *
26 * @category Common
27 * @package DmarcSrg
28 * @author Aleksey Andreev (liuch)
29 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
30 */
31
32 namespace Liuch\DmarcSrg;
33
34 /**
35 * The class is intended for displaying the table as text
36 * Usage example:
37 * (new TextTable([ 'Organization', 'Reports' ]))
38 * ->appendRow([ 'Organization 1', 15 ])
39 * ->appendRow([ 'Organization 2', 12 ])
40 * ->setMinColumnWidth(0, 25)
41 * ->sortBy(1)
42 * ->output();
43 *
44 */
45 class TextTable
46 {
47 private $columns = null;
48 private $sort_by = null;
49 private $row_list = [];
50 private $widths = null;
51 private $minimals = [];
52 private $alignment = [];
53 private $skeleton = [ 'border' => null, 'header' => null, 'data' => null ];
54 private $borders = [ 'horizontal' => '-', 'vertical' => '|', 'intersection' => '+' ];
55
56 /**
57 * Constructor
58 *
59 * @param array $columns Array of strings with column names
60 */
61 public function __construct(array $columns)
62 {
63 $this->columns = $columns;
64 }
65
66 /**
67 * Adds a row of with data to the table
68 *
69 * @param array $row_data Array with row data
70 *
71 * @retrun self
72 */
73 public function appendRow(array $row_data)
74 {
75 $this->row_list[] = $row_data;
76 return $this;
77 }
78
79 /**
80 * Sets the minimal width in characters for the specified column
81 *
82 * @param int $col Zero-based index of the column
83 * @param int $width Minimum column width
84 *
85 * @return self
86 */
87 public function setMinColumnWidth(int $col, int $width)
88 {
89 if ($col >= 0 && $col < count($this->columns) && $width >= 0) {
90 $this->minimals[$col] = $width;
91 }
92 return $this;
93 }
94
95 /**
96 * Sets the minimal width for in characters for the all columns at once
97 *
98 * If the array size is not the same as the number of columns, the extra or missing coulumns are ignored.
99 *
100 * @param array $widths
101 *
102 * @return self
103 */
104 public function setMinColumnsWidth(array $widths)
105 {
106 $c = min(count($widths), count($this->columns));
107 for ($i = 0; $i < $c; ++$i) {
108 if (is_int($widths[$i])) {
109 $this->minimals[$i] = $widths[$i];
110 }
111 }
112 return $this;
113 }
114
115 /**
116 * Adjusts data alignment in columns
117 *
118 * @param int $col Zero-based index of the column
119 * @param string $align Alignment value. Can be either `left` or `right`.
120 *
121 * @return self
122 */
123 public function setColumnAlignment(int $col, string $align)
124 {
125 if ($col >= 0 && $col < count($this->columns)) {
126 switch ($align) {
127 case 'left':
128 case 'right':
129 $this->alignment[$col] = $align;
130 }
131 }
132 return $this;
133 }
134
135 /**
136 * Sets the characters for the table borders
137 *
138 * @param string $horizontal Horizontal border
139 * @param string $vertical Vertical border
140 * @param string $intersection Border at intersections
141 *
142 * @return self
143 */
144 public function setBorders(string $horizontal, string $vertical, string $intersection)
145 {
146 $this->borders['horizontal'] = $horizontal;
147 $this->borders['vertical'] = $vertical;
148 $this->borders['intersection'] = $intersection;
149 return $this;
150 }
151
152 /**
153 * Specifies by which column the rows in the table should be sorted
154 *
155 * @param int $col Zero-based index of the column
156 *
157 * @return self
158 */
159 public function sortBy(int $col)
160 {
161 if ($col >= 0 && $col < count($this->columns)) {
162 $this->sort_by = $col;
163 }
164 return $this;
165 }
166
167 /**
168 * Outputs the final table view to stdout
169 *
170 * @return void
171 */
172 public function output(): void
173 {
174 foreach ($this->toArray() as $s) {
175 echo $s, PHP_EOL;
176 }
177 }
178
179 /**
180 * Returns the table as an array of text strings
181 *
182 * @return array
183 */
184 public function toArray(): array
185 {
186 $res = [];
187 $cc = count($this->columns);
188 if ($cc) {
189 $this->calculateWidths();
190 $this->makeSkeleton();
191 $bf = !empty($this->skeleton['border']);
192 if ($bf) {
193 $res[] = $this->skeleton['border'];
194 }
195 $res[] = $this->generateHeader();
196 if ($bf) {
197 $res[] = $this->skeleton['border'];
198 }
199 if (count($this->row_list)) {
200 $sort_by = $this->sort_by;
201 if (!is_null($sort_by) && isset($this->columns[$sort_by])) {
202 usort($this->row_list, static function ($a, $b) use ($sort_by) {
203 return $a[$sort_by] <=> $b[$sort_by];
204 });
205 }
206 foreach ($this->row_list as &$row) {
207 $res[] = $this->generateRow($row);
208 }
209 unset($row);
210 }
211 if ($bf) {
212 $res[] = $this->skeleton['border'];
213 }
214 }
215 return $res;
216 }
217
218 /**
219 * Pre-calculates column widths
220 *
221 * @return void
222 */
223 private function calculateWidths(): void
224 {
225 $this->widths = [];
226 for ($i = 0; $i < count($this->columns); ++$i) {
227 $width = max(mb_strlen(strval($this->columns[$i])), $this->minimals[$i] ?? 0);
228 foreach ($this->row_list as $row) {
229 $width = max($width, mb_strlen(strval($row[$i] ?? '')));
230 }
231 $this->widths[$i] = $width;
232 }
233 }
234
235 /**
236 * Creates templates for outputting table elements
237 *
238 * @return void
239 */
240 private function makeSkeleton(): void
241 {
242 $vborder = $this->borders['vertical'];
243 $hborder = $this->borders['horizontal'];
244 $iborder = $this->borders['intersection'];
245
246 $border = $iborder;
247 $header = $vborder;
248 $data = $vborder;
249 for ($i = 0; $i < count($this->widths); ++$i) {
250 $w = $this->widths[$i];
251 $border .= str_repeat($hborder, $w + 2) . $iborder;
252 $d = $this->row_list[0][$i] ?? '';
253 switch ($this->alignment[$i] ?? (is_int($d) ? 'right' : 'left')) {
254 case 'right':
255 $header .= " %{$w}s {$vborder}";
256 $data .= " %{$w}s {$vborder}";
257 break;
258 case 'left':
259 default:
260 $header .= " %-{$w}s {$vborder}";
261 $data .= " %-{$w}s {$vborder}";
262 break;
263 }
264 }
265 $this->skeleton['border'] = trim($border);
266 $this->skeleton['header'] = trim($header);
267 $this->skeleton['data'] = trim($data);
268 }
269
270 /**
271 * Makess a string with titles
272 *
273 * @return string
274 */
275 private function generateHeader(): string
276 {
277 return vsprintf($this->skeleton['header'], $this->columns);
278 }
279
280 /**
281 * Generates a table row
282 *
283 * @param array $columns Columns of the row
284 *
285 * @return string
286 */
287 private function generateRow(array $columns): string
288 {
289 return vsprintf($this->skeleton['data'], $columns);
290 }
291 }