Skip to content

Commit

Permalink
Refactor to extract methods for common logic
Browse files Browse the repository at this point in the history
  • Loading branch information
caendesilva committed Jul 25, 2024
1 parent 831c83c commit 851b17a
Showing 1 changed file with 20 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Hyde\Hyde;
use Illuminate\Support\Str;
use Hyde\Support\Models\Route;
use Hyde\Support\Filesystem\MediaFile;
use Hyde\Markdown\Contracts\MarkdownPostProcessorContract;

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

public static function postprocess(string $html): string
{
foreach (static::routeMap() as $sourcePath => $route) {
$patterns = [
sprintf('<a href="%s"', $sourcePath),
sprintf('<a href="/%s"', $sourcePath),
];
$html = static::processMap(static::routeMap(), $html, 'a', 'href');
$html = static::processMap(static::assetMap(), $html, 'img', 'src');

$html = str_replace($patterns, sprintf('<a href="%s"', $route->getLink()), $html);
}
return $html;
}

foreach (static::assetMap() as $sourcePath => $mediaFile) {
/**
* @param array<string, \Hyde\Support\Models\Route|\Hyde\Support\Filesystem\MediaFile> $map
*/
protected static function processMap(array $map, string $html, string $tag, string $attribute): string
{
foreach ($map as $sourcePath => $item) {
$patterns = [
sprintf('<img src="%s"', $sourcePath),
sprintf('<img src="/%s"', $sourcePath),
sprintf('<%s %s="%s"', $tag, $attribute, $sourcePath),
sprintf('<%s %s="/%s"', $tag, $attribute, $sourcePath),
];

$html = str_replace($patterns, sprintf('<img src="%s"', static::assetPath($mediaFile)), $html);
$replacement = sprintf('<%s %s="%s"', $tag, $attribute, static::getItemPath($item));
$html = str_replace($patterns, $replacement, $html);
}

return $html;
}

protected static function getItemPath(MediaFile|Route $item): string
{
return $item instanceof MediaFile ? static::assetPath($item) : $item->getLink();
}

/** @return array<string, \Hyde\Support\Models\Route> */
protected static function routeMap(): array
{
Expand Down

0 comments on commit 851b17a

Please sign in to comment.