Skip to content

Commit 851b17a

Browse files
committed
Refactor to extract methods for common logic
1 parent 831c83c commit 851b17a

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

packages/framework/src/Markdown/Processing/DynamicMarkdownLinkProcessor.php

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
use Hyde\Hyde;
88
use Illuminate\Support\Str;
9+
use Hyde\Support\Models\Route;
910
use Hyde\Support\Filesystem\MediaFile;
1011
use Hyde\Markdown\Contracts\MarkdownPostProcessorContract;
1112

@@ -16,27 +17,35 @@ class DynamicMarkdownLinkProcessor implements MarkdownPostProcessorContract
1617

1718
public static function postprocess(string $html): string
1819
{
19-
foreach (static::routeMap() as $sourcePath => $route) {
20-
$patterns = [
21-
sprintf('<a href="%s"', $sourcePath),
22-
sprintf('<a href="/%s"', $sourcePath),
23-
];
20+
$html = static::processMap(static::routeMap(), $html, 'a', 'href');
21+
$html = static::processMap(static::assetMap(), $html, 'img', 'src');
2422

25-
$html = str_replace($patterns, sprintf('<a href="%s"', $route->getLink()), $html);
26-
}
23+
return $html;
24+
}
2725

28-
foreach (static::assetMap() as $sourcePath => $mediaFile) {
26+
/**
27+
* @param array<string, \Hyde\Support\Models\Route|\Hyde\Support\Filesystem\MediaFile> $map
28+
*/
29+
protected static function processMap(array $map, string $html, string $tag, string $attribute): string
30+
{
31+
foreach ($map as $sourcePath => $item) {
2932
$patterns = [
30-
sprintf('<img src="%s"', $sourcePath),
31-
sprintf('<img src="/%s"', $sourcePath),
33+
sprintf('<%s %s="%s"', $tag, $attribute, $sourcePath),
34+
sprintf('<%s %s="/%s"', $tag, $attribute, $sourcePath),
3235
];
3336

34-
$html = str_replace($patterns, sprintf('<img src="%s"', static::assetPath($mediaFile)), $html);
37+
$replacement = sprintf('<%s %s="%s"', $tag, $attribute, static::getItemPath($item));
38+
$html = str_replace($patterns, $replacement, $html);
3539
}
3640

3741
return $html;
3842
}
3943

44+
protected static function getItemPath(MediaFile|Route $item): string
45+
{
46+
return $item instanceof MediaFile ? static::assetPath($item) : $item->getLink();
47+
}
48+
4049
/** @return array<string, \Hyde\Support\Models\Route> */
4150
protected static function routeMap(): array
4251
{

0 commit comments

Comments
 (0)