From 3c9006e0c5ac4d3f789616bd28c03fe38615844c Mon Sep 17 00:00:00 2001 From: ghost Date: Tue, 6 Feb 2024 02:21:45 +0200 Subject: [PATCH] add ASCII table support --- .gitignore | 2 ++ composer.json | 4 ++- src/Dokuwiki/Reader.php | 76 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 57872d0..05388a6 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ /vendor/ + +composer.lock \ No newline at end of file diff --git a/composer.json b/composer.json index ba906c9..efc7aa6 100644 --- a/composer.json +++ b/composer.json @@ -10,5 +10,7 @@ "Yggverse\\Gemini\\": "src/" } }, - "require": {} + "require": { + "dekor/php-array-table": "^2.0" + } } diff --git a/src/Dokuwiki/Reader.php b/src/Dokuwiki/Reader.php index 74339d0..1cc1478 100644 --- a/src/Dokuwiki/Reader.php +++ b/src/Dokuwiki/Reader.php @@ -4,6 +4,8 @@ declare(strict_types=1); namespace Yggverse\Gemini\Dokuwiki; +use dekor\ArrayToTextTable; + class Reader { private array $_macros = @@ -259,6 +261,80 @@ class Reader ); } + // ASCII table + $table = false; + + $rows = []; + + $th = []; + + foreach ($lines as $index => $line) + { + // Header + if (!$table && preg_match_all('/\^([^\^]+)/', $line, $matches)) + { + if (isset($matches[1]) && count($matches[1]) > 1) + { + $table = true; + + $rows = []; + + $th = []; + + foreach ($matches[1] as $value) + { + $th[] = trim( + $value + ); + } + + unset( + $lines[$index] + ); + + continue; + } + } + + // Body + if ($table) + { + $table = false; + + if (preg_match(sprintf('/%s\|/', str_repeat('\|(.*)', count($th))), $line, $matches)) + { + if (count($matches) == count($th) + 1) + { + $table = true; + + $row = []; + foreach ($th as $offset => $column) + { + $row[$column] = trim( + $matches[$offset + 1] + ); + } + + $rows[] = $row; + + unset( + $lines[$index] + ); + } + } + + if (!$table && $rows) + { + $builder = new ArrayToTextTable( + $rows + ); + + $lines[$index] = '```' . PHP_EOL . $builder->render() . PHP_EOL . '```'; + } + } + } + + // Merge lines return preg_replace( '/[\n\r]{2,}/', PHP_EOL . PHP_EOL,