Passed
Push — master ( fe43ea...fddb9c )
by
unknown
12:44
created

Url::getPattern()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Attribute;
8
use Closure;
9
use RuntimeException;
10
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait;
11
use Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait;
12
use Yiisoft\Validator\Rule\Trait\WhenTrait;
13
use Yiisoft\Validator\SerializableRuleInterface;
14
use Yiisoft\Validator\SkipOnEmptyInterface;
15
use Yiisoft\Validator\SkipOnErrorInterface;
16
use Yiisoft\Validator\ValidationContext;
17
use Yiisoft\Validator\WhenInterface;
18
19
use function function_exists;
20
21
/**
22
 * Validates that the value is a valid HTTP or HTTPS URL.
23
 *
24
 * Note that this rule only checks if the URL scheme and host part are correct.
25
 * It does not check the remaining parts of a URL.
26
 */
27
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
28
final class Url implements SerializableRuleInterface, SkipOnErrorInterface, WhenInterface, SkipOnEmptyInterface
29
{
30
    use SkipOnEmptyTrait;
31
    use SkipOnErrorTrait;
32
    use WhenTrait;
33
34 2
    public function __construct(
35
        /**
36
         * @var string the regular expression used to validate the value.
37
         * The pattern may contain a `{schemes}` token that will be replaced
38
         * by a regular expression which represents the {@see $schemes}.
39
         *
40
         * Note that if you want to reuse the pattern in HTML5 input it should have ^ and $, should not have any
41
         * modifiers and should not be case-insensitive.
42
         */
43
        private string $pattern = '/^{schemes}:\/\/(([a-zA-Z0-9][a-zA-Z0-9_-]*)(\.[a-zA-Z0-9][a-zA-Z0-9_-]*)+)(?::\d{1,5})?([?\/#].*$|$)/',
44
        /**
45
         * @var array list of URI schemes which should be considered valid. By default, http and https
46
         * are considered to be valid schemes.
47
         */
48
        private array $validSchemes = ['http', 'https'],
49
        /**
50
         * @var bool whether validation process should take into account IDN (internationalized
51
         * domain names). Defaults to false meaning that validation of URLs containing IDN will always
52
         * fail. Note that in order to use IDN validation you have to install and enable `intl` PHP
53
         * extension, otherwise an exception would be thrown.
54
         */
55
        private bool $enableIDN = false,
56
        private string $message = 'This value is not a valid URL.',
57
58
        /**
59
         * @var bool|callable|null
60
         */
61
        private $skipOnEmpty = null,
62
        private bool $skipOnError = false,
63
        /**
64
         * @var Closure(mixed, ValidationContext):bool|null
65
         */
66
        private ?Closure $when = null,
67
    ) {
68 2
        if ($enableIDN && !function_exists('idn_to_ascii')) {
69
            throw new RuntimeException('In order to use IDN validation intl extension must be installed and enabled.');
70
        }
71
    }
72
73 1
    public function getName(): string
74
    {
75 1
        return 'url';
76
    }
77
78 41
    public function getPattern(): string
79
    {
80 41
        if (str_contains($this->pattern, '{schemes}')) {
81 38
            return str_replace('{schemes}', '((?i)' . implode('|', $this->validSchemes) . ')', $this->pattern);
82
        }
83
84 3
        return $this->pattern;
85
    }
86
87
    /**
88
     * @return array|string[]
89
     */
90
    public function getValidSchemes(): array
91
    {
92
        return $this->validSchemes;
93
    }
94
95 37
    public function isEnableIDN(): bool
96
    {
97 37
        return $this->enableIDN;
98
    }
99
100 16
    public function getMessage(): string
101
    {
102 16
        return $this->message;
103
    }
104
105 4
    public function getOptions(): array
106
    {
107
        return [
108 4
            'pattern' => $this->getPattern(),
109 4
            'validSchemes' => $this->validSchemes,
110 4
            'enableIDN' => $this->enableIDN,
111
            'message' => [
112 4
                'message' => $this->message,
113
            ],
114 4
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
115 4
            'skipOnError' => $this->skipOnError,
116
        ];
117
    }
118
119 1
    public function getHandlerClassName(): string
120
    {
121 1
        return UrlHandler::class;
122
    }
123
}
124