1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Xparse\Parser\Helper; |
6
|
|
|
|
7
|
|
|
use GuzzleHttp\Psr7\Uri; |
8
|
|
|
use GuzzleHttp\Psr7\UriResolver; |
9
|
|
|
use Xparse\ElementFinder\ElementFinder\ElementFinderModifierInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* @internal |
13
|
|
|
* @author Ivan Shcherbak <[email protected]> |
14
|
|
|
*/ |
15
|
|
|
class ConvertUrlElementFinderModifier implements ElementFinderModifierInterface { |
16
|
|
|
|
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var string |
20
|
|
|
*/ |
21
|
|
|
private $affectedUrl; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var string |
25
|
|
|
*/ |
26
|
|
|
private $baseUrl; |
27
|
|
|
|
28
|
|
|
|
29
|
|
|
public function __construct(string $affectedUrl, string $baseUrl) { |
30
|
|
|
$this->affectedUrl = $affectedUrl; |
31
|
|
|
$this->baseUrl = $baseUrl; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param \DOMNodeList $nodeList |
37
|
|
|
* @return void |
38
|
|
|
*/ |
39
|
|
|
public function modify(\DOMNodeList $nodeList) { |
40
|
|
|
$affected = new Uri($this->affectedUrl); |
41
|
|
|
foreach ($nodeList as $element) { |
42
|
|
|
/** @var \DOMElement $element */ |
43
|
|
|
$attribute = $this->attributeName($element); |
44
|
|
|
$relative = $element->getAttribute($attribute); |
45
|
|
|
$isValid = parse_url($relative) !== false; |
46
|
|
|
if ( |
47
|
|
|
!preg_match('!^\s*javascript\s*:\s*!', $relative) |
48
|
|
|
and |
49
|
|
|
$isValid |
50
|
|
|
) { |
51
|
|
|
if ($this->baseUrl !== '' and !preg_match('!^(/|http)!i', $relative)) { |
52
|
|
|
$relative = UriResolver::resolve(new Uri($this->baseUrl), new Uri($relative)); |
53
|
|
|
} |
54
|
|
|
$url = UriResolver::resolve($affected, new Uri($relative)); |
|
|
|
|
55
|
|
|
$element->setAttribute($attribute, (string) $url); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @param \DOMElement $element |
63
|
|
|
* @return string |
64
|
|
|
*/ |
65
|
|
|
private function attributeName(\DOMElement $element): string { |
66
|
|
|
$name = 'href'; |
67
|
|
|
if ($element->tagName === 'form' and $element->hasAttribute('action') === true) { |
68
|
|
|
$name = 'action'; |
69
|
|
|
} else if ($element->hasAttribute('src') === true) { |
70
|
|
|
$name = 'src'; |
71
|
|
|
} |
72
|
|
|
return $name; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
} |
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.