Passed
Push — master ( 054509...a8959a )
by Enjoys
01:55
created

ReplaceRelativeUrls::setLogger()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\AssetsCollector\Content;
6
7
use Enjoys\UrlConverter;
8
use Psr\Log\LoggerInterface;
9
use Psr\Log\NullLogger;
10
11
/**
12
 * Class ReplaceRelativeUrls
13
 * @package Enjoys\AssetsCollector\Content
14
 */
15
class ReplaceRelativeUrls
16
{
17
    private string $content;
18
    private string $url;
19
    private LoggerInterface $logger;
20
21 3
    public function __construct(string $content, string $url)
22
    {
23 3
        $this->content = $content;
24 3
        $this->logger = new NullLogger();
25 3
        $this->url = $url;
26 3
    }
27
28
29
    /**
30
     * @return string
31
     */
32 3
    public function getContent(): string
33
    {
34 3
        $result = preg_replace_callback(
35 3
            '/(url\([\'"]?)(?!["\'a-z]+:|[\'"]?\/{2})(.+[^\'"])([\'"]?\))/i',
36 3
            function (array $m) {
37
                /** @var string[] $m */
38 3
                $urlConverter = new UrlConverter();
39
40
                /** @var string|false $urlNormalized */
41 3
                $urlNormalized = $urlConverter->relativeToAbsolute($this->url, $m[2]);
42 3
                if ($urlNormalized === false) {
0 ignored issues
show
introduced by
The condition $urlNormalized === false is always true.
Loading history...
43
                    return $m[1] . $m[2] . $m[3];
44
                }
45
46 3
                return $m[1] . $urlNormalized . $m[3];
47 3
            },
48 3
            $this->content
49
        );
50
51 3
        if ($result === null) {
52
            $this->logger->notice(sprintf('Regex return null value. Returned empty string: %s', $this->url));
53
            return '';
54
        }
55 3
        $this->logger->info(sprintf('ReplaceRelativeUrls: %s', $this->url));
56 3
        return $result;
57
    }
58
59
    /**
60
     * @param LoggerInterface|NullLogger $logger
61
     */
62
    public function setLogger($logger): void
63
    {
64
        $this->logger = $logger;
65
    }
66
67
68
}
69