|
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 Zend\Diactoros\Uri; |
|
13
|
|
|
|
|
14
|
|
|
use function idn_to_ascii; |
|
15
|
|
|
|
|
16
|
|
|
use const IDNA_DEFAULT; |
|
17
|
|
|
use const INTL_IDNA_VARIANT_UTS46; |
|
18
|
|
|
|
|
19
|
|
|
class UrlValidator implements UrlValidatorInterface, RequestMethodInterface |
|
20
|
|
|
{ |
|
21
|
|
|
private const MAX_REDIRECTS = 15; |
|
22
|
|
|
|
|
23
|
|
|
/** @var ClientInterface */ |
|
24
|
|
|
private $httpClient; |
|
25
|
|
|
|
|
26
|
3 |
|
public function __construct(ClientInterface $httpClient) |
|
27
|
|
|
{ |
|
28
|
3 |
|
$this->httpClient = $httpClient; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @throws InvalidUrlException |
|
33
|
|
|
*/ |
|
34
|
3 |
|
public function validateUrl(string $url): void |
|
35
|
|
|
{ |
|
36
|
|
|
// FIXME Guzzle is about to add support for this https://github.com/guzzle/guzzle/pull/2286 |
|
37
|
|
|
// Remove custom implementation when Guzzle's PR is merged |
|
38
|
3 |
|
$uri = new Uri($url); |
|
39
|
3 |
|
$originalHost = $uri->getHost(); |
|
40
|
3 |
|
$normalizedHost = idn_to_ascii($originalHost, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46); |
|
41
|
3 |
|
if ($originalHost !== $normalizedHost) { |
|
42
|
1 |
|
$uri = $uri->withHost($normalizedHost); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
try { |
|
46
|
3 |
|
$this->httpClient->request(self::METHOD_GET, (string) $uri, [ |
|
47
|
3 |
|
RequestOptions::ALLOW_REDIRECTS => ['max' => self::MAX_REDIRECTS], |
|
48
|
|
|
]); |
|
49
|
1 |
|
} catch (GuzzleException $e) { |
|
50
|
1 |
|
throw InvalidUrlException::fromUrl($url, $e); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|