Test Failed
Pull Request — master (#222)
by Rustam
02:30
created

UrlHandler::convertIdn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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