Passed
Pull Request — master (#222)
by Alexander
04:26 queued 02:14
created

Url   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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