Passed
Pull Request — master (#320)
by Dmitriy
12:15 queued 09:25
created

UrlHandler   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 20
c 1
b 0
f 0
dl 0
loc 46
ccs 21
cts 21
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A convertIdn() 0 10 2
A validate() 0 25 6
A idnToAscii() 0 5 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\Exception\UnexpectedRuleException;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\RuleHandlerInterface;
10
use Yiisoft\Validator\ValidationContext;
11
12
use function is_string;
13
use function strlen;
14
15
/**
16
 * Validates that the value is a valid HTTP or HTTPS URL.
17
 *
18
 * Note that this rule only checks if the URL scheme and host part are correct.
19
 * It does not check the remaining parts of a URL.
20
 */
21
final class UrlHandler implements RuleHandlerInterface
22
{
23 39
    public function validate(mixed $value, object $rule, ValidationContext $context): Result
24
    {
25 39
        if (!$rule instanceof Url) {
26 1
            throw new UnexpectedRuleException(Url::class, $rule);
27
        }
28
29 38
        $result = new Result();
30
31
        // make sure the length is limited to avoid DOS attacks
32 38
        if (is_string($value) && strlen($value) < 2000) {
33 37
            if ($rule->isEnableIDN()) {
34 5
                $value = $this->convertIdn($value);
35
            }
36
37 37
            if (preg_match($rule->getPattern(), $value)) {
38 22
                return $result;
39
            }
40
        }
41
42 16
        $result->addError(
43 16
            message: $rule->getMessage(),
44 16
            parameters: ['value' => $value]
45
        );
46
47 16
        return $result;
48
    }
49
50 5
    private function idnToAscii(string $idn): string
51
    {
52 5
        $result = idn_to_ascii($idn, 0, INTL_IDNA_VARIANT_UTS46);
53
54 5
        return $result === false ? '' : $result;
55
    }
56
57 5
    private function convertIdn(string $value): string
58
    {
59 5
        if (!str_contains($value, '://')) {
60 3
            return $this->idnToAscii($value);
61
        }
62
63 2
        return preg_replace_callback(
64
            '/:\/\/([^\/]+)/',
65 2
            fn ($matches) => '://' . $this->idnToAscii($matches[1]),
66
            $value
67
        );
68
    }
69
}
70