Passed
Push — master ( 4437d5...b3ea29 )
by Alejandro
04:00 queued 13s
created

UrlValidator::validateUrl()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 10
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 17
rs 9.9332
ccs 10
cts 10
cp 1
crap 3
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