|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Michalsn\CodeIgniterHtmx\Format; |
| 4 | + |
| 5 | +use CodeIgniter\Format\FormatterInterface; |
| 6 | +use CodeIgniter\View\Table; |
| 7 | + |
| 8 | +/** |
| 9 | + * HTML data formatter |
| 10 | + */ |
| 11 | +class HTMLFormatter implements FormatterInterface |
| 12 | +{ |
| 13 | + /** |
| 14 | + * Takes the given data and formats it. |
| 15 | + * |
| 16 | + * @param array|string|null $data |
| 17 | + */ |
| 18 | + public function format($data): string |
| 19 | + { |
| 20 | + if ($data === null || $data === '' || $data === []) { |
| 21 | + return ''; |
| 22 | + } |
| 23 | + |
| 24 | + if (is_array($data)) { |
| 25 | + if (array_keys($data) === ['status', 'error', 'messages']) { |
| 26 | + if (isset($data['messages']['error']) && count($data['messages']) === 1) { |
| 27 | + return $data['messages']['error']; |
| 28 | + } |
| 29 | + |
| 30 | + $data = $data['messages']; |
| 31 | + } |
| 32 | + |
| 33 | + $data = $this->formatTable($data); |
| 34 | + } |
| 35 | + |
| 36 | + return $data; |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Format data as a table. |
| 41 | + * |
| 42 | + * @param mixed $data |
| 43 | + */ |
| 44 | + protected function formatTable($data): string |
| 45 | + { |
| 46 | + if (isset($data[0]) && count($data) !== count($data, COUNT_RECURSIVE)) { |
| 47 | + // Multi-dimensional array |
| 48 | + $headings = array_keys($data[0]); |
| 49 | + } else { |
| 50 | + // Single array |
| 51 | + $headings = array_keys($data); |
| 52 | + $data = [$data]; |
| 53 | + } |
| 54 | + |
| 55 | + $table = new Table(); |
| 56 | + $table->setHeading($headings); |
| 57 | + |
| 58 | + foreach ($data as $row) { |
| 59 | + // Suppressing the "array to string conversion" notice |
| 60 | + // Keep the "evil" @ here |
| 61 | + $row = @array_map('strval', $row); |
| 62 | + |
| 63 | + $table->addRow($row); |
| 64 | + } |
| 65 | + |
| 66 | + return $table->generate(); |
| 67 | + } |
| 68 | +} |
0 commit comments