1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Shlinkio\Shlink\Core\Util; |
6
|
|
|
|
7
|
|
|
use Fig\Http\Message\RequestMethodInterface; |
8
|
|
|
use GuzzleHttp\ClientInterface; |
9
|
|
|
use GuzzleHttp\Exception\GuzzleException; |
10
|
|
|
use GuzzleHttp\RequestOptions; |
11
|
|
|
use Shlinkio\Shlink\Core\Exception\InvalidUrlException; |
12
|
|
|
use Shlinkio\Shlink\Core\Options\UrlShortenerOptions; |
13
|
|
|
|
14
|
|
|
class UrlValidator implements UrlValidatorInterface, RequestMethodInterface |
15
|
|
|
{ |
16
|
|
|
private const MAX_REDIRECTS = 15; |
17
|
|
|
|
18
|
|
|
private ClientInterface $httpClient; |
19
|
|
|
private UrlShortenerOptions $options; |
20
|
|
|
|
21
|
6 |
|
public function __construct(ClientInterface $httpClient, UrlShortenerOptions $options) |
22
|
|
|
{ |
23
|
6 |
|
$this->httpClient = $httpClient; |
24
|
6 |
|
$this->options = $options; |
25
|
6 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @throws InvalidUrlException |
29
|
|
|
*/ |
30
|
6 |
|
public function validateUrl(string $url, ?bool $doValidate): void |
31
|
|
|
{ |
32
|
|
|
// If the URL validation is not enabled or it was explicitly set to not validate, skip check |
33
|
6 |
|
$doValidate = $doValidate ?? $this->options->isUrlValidationEnabled(); |
34
|
6 |
|
if (! $doValidate) { |
35
|
3 |
|
return; |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
try { |
39
|
3 |
|
$this->httpClient->request(self::METHOD_GET, $url, [ |
40
|
3 |
|
RequestOptions::ALLOW_REDIRECTS => ['max' => self::MAX_REDIRECTS], |
41
|
3 |
|
RequestOptions::IDN_CONVERSION => true, |
42
|
|
|
]); |
43
|
2 |
|
} catch (GuzzleException $e) { |
44
|
2 |
|
throw InvalidUrlException::fromUrl($url, $e); |
45
|
|
|
} |
46
|
2 |
|
} |
47
|
|
|
} |
48
|
|
|
|