1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Hyde\Markdown\Processing; |
6
|
|
|
|
7
|
|
|
use Hyde\Hyde; |
8
|
|
|
use Illuminate\Support\Str; |
9
|
|
|
use Hyde\Support\Filesystem\MediaFile; |
10
|
|
|
use Hyde\Markdown\Contracts\MarkdownPostProcessorContract; |
11
|
|
|
|
12
|
|
|
class DynamicMarkdownLinkProcessor implements MarkdownPostProcessorContract |
13
|
|
|
{ |
14
|
|
|
/** @var array<string, \Hyde\Support\Filesystem\MediaFile>|null */ |
15
|
|
|
protected static ?array $assetMapCache = null; |
16
|
|
|
|
17
|
|
|
public static function postprocess(string $html): string |
18
|
|
|
{ |
19
|
|
|
foreach (static::routeMap() as $sourcePath => $route) { |
20
|
|
|
$patterns = [ |
21
|
|
|
sprintf('<a href="%s"', $sourcePath), |
22
|
|
|
sprintf('<a href="/%s"', $sourcePath), |
23
|
|
|
]; |
24
|
|
|
|
25
|
|
|
$html = str_replace($patterns, sprintf('<a href="%s"', $route->getLink()), $html); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
foreach (static::assetMap() as $sourcePath => $mediaFile) { |
29
|
|
|
$patterns = [ |
30
|
|
|
sprintf('<img src="%s"', $sourcePath), |
31
|
|
|
sprintf('<img src="/%s"', $sourcePath), |
32
|
|
|
]; |
33
|
|
|
|
34
|
|
|
$html = str_replace($patterns, sprintf('<img src="%s"', static::assetPath($mediaFile)), $html); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return $html; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** @return array<string, \Hyde\Support\Models\Route> */ |
41
|
|
|
protected static function routeMap(): array |
42
|
|
|
{ |
43
|
|
|
$map = []; |
44
|
|
|
|
45
|
|
|
/** @var \Hyde\Support\Models\Route $route */ |
46
|
|
|
foreach (Hyde::routes() as $route) { |
|
|
|
|
47
|
|
|
$map[$route->getSourcePath()] = $route; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return $map; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** @return array<string, \Hyde\Support\Filesystem\MediaFile> */ |
54
|
|
|
protected static function assetMap(): array |
55
|
|
|
{ |
56
|
|
|
if (static::$assetMapCache === null) { |
57
|
|
|
static::$assetMapCache = []; |
58
|
|
|
|
59
|
|
|
foreach (MediaFile::all() as $mediaFile) { |
60
|
|
|
static::$assetMapCache[$mediaFile->getPath()] = $mediaFile; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return static::$assetMapCache; |
|
|
|
|
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
protected static function assetPath(MediaFile $mediaFile): string |
68
|
|
|
{ |
69
|
|
|
return Hyde::asset(Str::after($mediaFile->getPath(), '_media/'))->getLink(); |
|
|
|
|
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** @internal Testing helper to reset the asset map cache. */ |
73
|
|
|
public static function resetAssetMapCache(): void |
74
|
|
|
{ |
75
|
|
|
static::$assetMapCache = null; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|