-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAttachmentLinkResolver.php
49 lines (40 loc) · 1.39 KB
/
AttachmentLinkResolver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
namespace Elazar\LeagueCommonMarkObsidian\Resolver;
use Elazar\LeagueCommonMarkObsidian\Iterator\FileIterator;
use Elazar\LeagueCommonMarkObsidian\RelativePathTrait;
class AttachmentLinkResolver implements LinkResolverInterface
{
use RelativePathTrait;
private string $vaultPath;
private \Traversable $iterator;
/**
* @var array<string, string>
*/
private array $cache = [];
public function __construct(
string $vaultPath,
string $attachmentsPath,
) {
$this->iterator = new FileIterator($attachmentsPath);
$this->vaultPath = realpath($vaultPath) . DIRECTORY_SEPARATOR;
}
public function resolve(string $name, string $fromPath): string
{
if (isset($this->cache[$name])) {
$toPath = $this->cache[$name];
} else {
foreach ($this->iterator as $entry) {
if ($entry->getFilename() === $name) {
$toPath = $this->cache[$name] = str_replace($this->vaultPath, '', $entry->getPathname());
break;
}
}
if (!isset($toPath)) {
throw LinkResolverException::failedToResolve($name);
}
}
$relativeFromPath = str_replace($this->vaultPath, '', $fromPath);
$resolvedPath = $this->getRelativePath($relativeFromPath, $toPath);
return $resolvedPath;
}
}