1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Xparse\Parser\Helper; |
6
|
|
|
|
7
|
|
|
use DOMNodeList; |
8
|
|
|
use GuzzleHttp\Psr7\Uri; |
9
|
|
|
use GuzzleHttp\Psr7\UriResolver; |
10
|
|
|
use Xparse\ElementFinder\DomNodeListAction\DomNodeListActionInterface; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @internal |
14
|
|
|
* @author Ivan Shcherbak <[email protected]> |
15
|
|
|
*/ |
16
|
|
|
class ConvertUrlElementFinderModifier implements DomNodeListActionInterface |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var string |
21
|
|
|
*/ |
22
|
|
|
private $affectedUrl; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
private $baseUrl; |
28
|
|
|
|
29
|
|
|
|
30
|
|
|
public function __construct(string $affectedUrl, string $baseUrl) |
31
|
|
|
{ |
32
|
|
|
$this->affectedUrl = $affectedUrl; |
33
|
|
|
$this->baseUrl = $baseUrl; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
|
37
|
|
|
final public function execute(DOMNodeList $nodeList): void |
38
|
|
|
{ |
39
|
|
|
$affected = new Uri($this->affectedUrl); |
40
|
|
|
foreach ($nodeList as $element) { |
41
|
|
|
/** @var \DOMElement $element */ |
42
|
|
|
$attribute = $this->attributeName($element); |
43
|
|
|
$relative = $element->getAttribute($attribute); |
44
|
|
|
$isValid = parse_url($relative) !== false; |
45
|
|
|
if ( |
46
|
|
|
$isValid |
47
|
|
|
&& |
48
|
|
|
!preg_match('!^\s*javascript\s*:\s*!', $relative) |
49
|
|
|
) { |
50
|
|
|
if ($this->baseUrl !== '' && !preg_match('!^(/|http)!i', $relative)) { |
51
|
|
|
$relative = UriResolver::resolve(new Uri($this->baseUrl), new Uri($relative)); |
52
|
|
|
} |
53
|
|
|
$url = UriResolver::resolve($affected, new Uri($relative)); |
|
|
|
|
54
|
|
|
/** @noinspection UnusedFunctionResultInspection */ |
55
|
|
|
$element->setAttribute($attribute, (string)$url); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
|
61
|
|
|
private function attributeName(\DOMElement $element): string |
62
|
|
|
{ |
63
|
|
|
$name = 'href'; |
64
|
|
|
if ($element->tagName === 'form' && $element->hasAttribute('action') === true) { |
65
|
|
|
$name = 'action'; |
66
|
|
|
} else if ($element->hasAttribute('src') === true) { |
67
|
|
|
$name = 'src'; |
68
|
|
|
} |
69
|
|
|
return $name; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
} |
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.