Completed
Push — master ( 5312d4...9560c6 )
by Pavel
07:34
created

MacroInlineFileLink   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
wmc 3
lcom 0
cbo 1
dl 0
loc 46
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B runMacro() 0 36 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ublaboo\Anabelle\Markdown\Macros;
6
7
use Nette\Utils\Html;
8
use Ublaboo\Anabelle\Generator\Exception\DocuGeneratorException;
9
10
final class MacroInlineFileLink implements IMacro
11
{
12
13
	const LINK_PATTERN = '/\[((?:[^][]++|(?R))*+)\]\(([^\)]*)\)/um';
14
15
16
	/**
17
	 * @throws DocuGeneratorException
18
	 */
19
	public function runMacro(
20
		string $inputDirectory,
21
		string $outputDirectory,
22
		string & $content // Intentionally &
23
	): void
24
	{
25
		/**
26
		 * Substitute "#include" macros with actual files
27
		 */
28
		$content = preg_replace_callback(
29
			self::LINK_PATTERN,
30
			function(array $input) use ($inputDirectory, $outputDirectory): string {
31
				$text = $input[1];
32
				$path = trim($input[2], '/');
33
34
				if (file_exists($inputDirectory . '/' . $path)) {
35
					$targetPath = str_replace(['../', './'], '', $outputDirectory . '/' . $path);
36
37
					if (!file_exists(dirname($targetPath))) {
38
						mkdir(dirname($targetPath), 0755, true);
39
					}
40
41
					copy($inputDirectory . '/' . $path, $targetPath);
42
43
					$targetPath = preg_replace('~^[^/]+/~', '', $targetPath);
44
45
					return (string) Html::el('a')->href($targetPath)
46
						->setText($text)
47
						->target('_blank');
48
				}
49
50
				return "[$text]($path)";
51
			},
52
			$content
53
		);
54
	}
55
}
56