1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
namespace Enjoys\AssetsCollector\Content; |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
use Enjoys\AssetsCollector\Environment; |
10
|
|
|
use Enjoys\AssetsCollector\Helpers; |
11
|
|
|
use Psr\Log\LoggerInterface; |
12
|
|
|
use Psr\Log\NullLogger; |
13
|
|
|
|
14
|
|
|
final class ReplaceRelativePaths |
15
|
|
|
{ |
16
|
|
|
private string $content; |
17
|
|
|
private string $path; |
18
|
|
|
private Environment $environment; |
19
|
|
|
private LoggerInterface $logger; |
20
|
|
|
|
21
|
9 |
|
public function __construct(string $content, string $path, Environment $environment) |
22
|
|
|
{ |
23
|
9 |
|
$this->environment = $environment; |
24
|
9 |
|
$this->content = $content; |
25
|
9 |
|
$this->logger = new NullLogger(); |
26
|
9 |
|
$this->path = pathinfo($path, PATHINFO_DIRNAME) . DIRECTORY_SEPARATOR; |
|
|
|
|
27
|
9 |
|
} |
28
|
|
|
|
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @return string |
32
|
|
|
* @throws \Exception |
33
|
|
|
*/ |
34
|
9 |
|
public function getContent(): string |
35
|
|
|
{ |
36
|
9 |
|
$result = preg_replace_callback( |
37
|
9 |
|
'/(url\([\'"]?)(?!["\'a-z]+:|[\'"]?\/{2})(.+?[^\'"])([\'"]?\))/i', |
38
|
9 |
|
function (array $m) { |
39
|
|
|
/** @var string[] $m */ |
40
|
6 |
|
$realpath = realpath($this->path . parse_url($m[2], PHP_URL_PATH)); |
41
|
|
|
|
42
|
6 |
|
if ($realpath === false) { |
43
|
2 |
|
return $m[1] . $m[2] . $m[3]; |
44
|
|
|
} |
45
|
5 |
|
$relativeFullPath = \str_replace( |
46
|
5 |
|
'\\', |
47
|
5 |
|
'/', |
48
|
5 |
|
\str_replace( |
49
|
|
|
[ |
50
|
5 |
|
$this->environment->getCompileDir(), |
51
|
5 |
|
$this->environment->getProjectDir() |
52
|
|
|
] |
53
|
|
|
, |
54
|
5 |
|
'', |
55
|
5 |
|
$realpath |
56
|
|
|
) |
57
|
|
|
); |
58
|
|
|
|
59
|
5 |
|
Helpers::createSymlink($this->environment->getCompileDir() . $relativeFullPath, $realpath, $this->logger); |
60
|
|
|
|
61
|
5 |
|
return $m[1] . $this->environment->getBaseUrl() . $relativeFullPath . $m[3]; |
62
|
9 |
|
}, |
63
|
9 |
|
$this->content |
64
|
|
|
); |
65
|
|
|
|
66
|
9 |
|
if ($result === null) { |
67
|
|
|
$this->logger->notice(sprintf('Regex return null value. Returned empty string: %s', $this->path)); |
68
|
|
|
return ''; |
69
|
|
|
} |
70
|
9 |
|
$this->logger->info(sprintf('ReplaceRelativePaths: %s', $this->path)); |
71
|
9 |
|
return $result; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @param LoggerInterface|NullLogger $logger |
76
|
|
|
*/ |
77
|
4 |
|
public function setLogger($logger): void |
78
|
|
|
{ |
79
|
4 |
|
$this->logger = $logger; |
80
|
|
|
} |
81
|
|
|
} |