From 11e1179976529272cb3acb53962097b35d347b4a Mon Sep 17 00:00:00 2001 From: Mathieu Ducrot Date: Wed, 12 Jun 2024 09:06:03 +0200 Subject: [PATCH] Add MarkdownUtils to help formatting markdown content before being render as html --- CHANGELOG.md | 4 ++ src/Utils/MarkdownUtils.php | 38 +++++++++++++ tests/Utils/MarkdownUtilsTest.php | 93 +++++++++++++++++++++++++++++++ 3 files changed, 135 insertions(+) create mode 100644 src/Utils/MarkdownUtils.php create mode 100644 tests/Utils/MarkdownUtilsTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index bdd02cd..ab3e355 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ CHANGELOG for 1.x =================== +## v1.6.0 - (2024-06-12) +### Added +- `MarkdownUtils` to help formatting markdown content before being render as html + ## v1.5.0 - (2024-06-10) ### Added - `ProcessTrait::restartedAt` Used to know when we wanted to retry this process (creating a new dedicated process based on this one) diff --git a/src/Utils/MarkdownUtils.php b/src/Utils/MarkdownUtils.php new file mode 100644 index 0000000..16c6659 --- /dev/null +++ b/src/Utils/MarkdownUtils.php @@ -0,0 +1,38 @@ + + */ +class MarkdownUtils +{ + /** + * @param string $md '# Heading #{"id": "heading"}' + * @param string $baseUrl 'http://url.test' + * @return string '# Heading' + */ + public static function addAnchorToHeadings(string $md, string $baseUrl): string + { + foreach (u($md)->match('/# .* #{.*}/', PREG_PATTERN_ORDER)[0] as $heading) { + $lastHashIndex = u($heading)->indexOfLast('#'); + $text = u($heading)->slice(1, $lastHashIndex - 1)->toString(); + $data = json_decode(u($heading)->slice($lastHashIndex + 1)->toString(), true); + $id = $data['id'] ?? null; + if ($id === null) { + continue; + } + $anchoredHeading = sprintf( + '# %s', + $baseUrl . '#' . $id, + $id, + trim($text), + ); + $md = u($md)->replace($heading, $anchoredHeading)->toString(); + } + + return $md; + } +} diff --git a/tests/Utils/MarkdownUtilsTest.php b/tests/Utils/MarkdownUtilsTest.php new file mode 100644 index 0000000..387f6d3 --- /dev/null +++ b/tests/Utils/MarkdownUtilsTest.php @@ -0,0 +1,93 @@ +assertEquals($expected, MarkdownUtils::addAnchorToHeadings($md, $baseUrl)); + } + + public function addAnchorToHeadingsProvider(): array + { + $baseUrl = 'http://url.test'; + + return [ + 'without heading' => [ + 'Texte', + 'Texte', + $baseUrl, + ], + 'heading without anchor' => [ + '# Heading', + '# Heading', + $baseUrl, + ], + 'heading with anchor' => [ + '# Heading', + '# Heading #{"id": "heading"}', + $baseUrl, + ], + 'heading with anchor + text before and after which need to be untouched after formatting' => [ + <<Heading +Texte Après +EOD, + << [ + <<Heading +Texte Après +EOD, + << [ + <<Heading A +## Heading B +EOD, + << [ + <<Heading 1 +## Heading 2 +### Heading 3 +EOD, + <<