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