Passed
Pull Request — master (#474)
by
unknown
02:24
created

Url::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 14
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 3
eloc 2
c 3
b 0
f 0
nc 2
nop 8
dl 0
loc 14
ccs 3
cts 3
cp 1
crap 3
rs 10

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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\RuleWithOptionsInterface;
14
use Yiisoft\Validator\SkipOnEmptyInterface;
15
use Yiisoft\Validator\SkipOnErrorInterface;
16
use Yiisoft\Validator\WhenInterface;
17
18
use function function_exists;
19
20
/**
21
 * Validates that the value is a valid HTTP or HTTPS URL.
22
 *
23
 * Note that this rule only checks if the URL scheme and host parts are correct.
24
 * It does not check the remaining parts of a URL.
25
 *
26
 * @psalm-import-type WhenType from WhenInterface
27
 *
28
 * @see UrlHandler
29
 */
30
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
31
final class Url implements RuleWithOptionsInterface, SkipOnErrorInterface, WhenInterface, SkipOnEmptyInterface
32
{
33
    use SkipOnEmptyTrait;
34 4
    use SkipOnErrorTrait;
35
    use WhenTrait;
36
37
    /**
38
     * @param string $pattern The regular expression used to validate the value.
39
     * The pattern may contain a `{schemes}` token that will be replaced
40
     * by a regular expression which represents the {@see $schemes}.
41
     *
42
     * Note that if you want to reuse the pattern in HTML5 input, it should have `^` and `$`, should not have any
43
     * modifiers and should not be case-insensitive.
44
     * @param string[] $validSchemes List of URI schemes which should be considered valid. By default, http and https
45
     * are considered to be valid schemes.
46
     * @param bool $enableIdn Whether the validation process must take
47
     * {@link https://en.wikipedia.org/wiki/Internationalized_domain_name IDN (internationalized domain names)}
48
     * into account . Defaults to `false` means that validation of URLs containing IDN will always
49
     * fail. Note that in order to use IDN validation you have to install and enable `intl` PHP
50
     * extension, otherwise an exception will be thrown.
51
     * @param string $incorrectInputMessage A message used when the input is incorrect.
52
     *
53
     * You may use the following placeholders in the message:
54
     *
55
     * - `{attribute}`: the label of the attribute being validated.
56
     * - `{type}`: the value's type.
57
     * @param string $message @var string A message used when the value is not valid.
58
     *
59
     * You may use the following placeholders in the message:
60
     *
61
     * - `{attribute}`: the label of the attribute being validated.
62
     * - `{value}`: the value of the attribute being validated.
63
     * @param bool|callable|null $skipOnEmpty Whether to skip this rule if the validated value is empty. See {@see SkipOnEmptyInterface}.
64
     * @param bool $skipOnError Whether to skip this rule if any of the previous rules gave an error. See {@see SkipOnErrorInterface}.
65
     * @param Closure|null $when A callable to define a condition for applying the rule. See {@see WhenInterface}.
66
     * @psalm-param WhenType $when
67
     */
68
    public function __construct(
69 4
        private string $pattern = '/^{schemes}:\/\/(([a-zA-Z0-9][a-zA-Z0-9_-]*)(\.[a-zA-Z0-9][a-zA-Z0-9_-]*)+)(?::\d{1,5})?([?\/#].*$|$)/',
70
        private array $validSchemes = ['http', 'https'],
71
        private bool $enableIdn = false,
72
        private string $incorrectInputMessage = 'The value must have a string type.',
73
        private string $message = 'This value is not a valid URL.',
74
        private $skipOnEmpty = null,
75
        private bool $skipOnError = false,
76
        private Closure|null $when = null,
77 1
    ) {
78
        if ($enableIdn && !function_exists('idn_to_ascii')) {
79 1
            // Tested via separate CI configuration (see ".github/workflows/build.yml").
80
            // @codeCoverageIgnoreStart
81
            throw new RuntimeException('In order to use IDN validation intl extension must be installed and enabled.');
82 44
            // @codeCoverageIgnoreEnd
83
        }
84 44
    }
85
86
    public function getName(): string
87
    {
88
        return 'url';
89
    }
90 2
91
    /**
92 2
     * Get ready to use regular expression pattern applied for URL validation.
93
     *
94
     * @return string Regular expression pattern applied for URL validation.
95 40
     */
96
    public function getPattern(): string
97 40
    {
98
        return str_replace('{schemes}', '((?i)' . implode('|', $this->validSchemes) . ')', $this->pattern);
99
    }
100 6
101
    /**
102 6
     * Get valid URI schemas.
103
     *
104
     * @return string[] List of URI schemes which should be considered valid. By default, http and https
105 19
     * are considered to be valid schemes.
106
     *
107 19
     * @see $validSchemes
108
     */
109
    public function getValidSchemes(): array
110 4
    {
111
        return $this->validSchemes;
112
    }
113 4
114 4
    /**
115 4
     * Whether the validation process must take
116
     * {@link https://en.wikipedia.org/wiki/Internationalized_domain_name IDN (internationalized domain names)}
117 4
     * into account. `false` means that validation of URLs containing IDN will always
118
     * fail. Note that in order to use IDN validation you have to install and enable `intl` PHP
119
     * extension, otherwise an exception will be thrown.
120
     *
121 4
     * @return bool Whether to enable IDN validation.
122
     *
123
     * @see $enableIdn
124 4
     */
125 4
    public function isIdnEnabled(): bool
126
    {
127
        return $this->enableIdn;
128
    }
129 48
130
    /**
131 48
     * Get a message used when the input is incorrect.
132
     *
133
     * @return string Error message.
134
     *
135
     * @see $incorrectInputMessage
136
     */
137
    public function getIncorrectInputMessage(): string
138
    {
139
        return $this->incorrectInputMessage;
140
    }
141
142
    /**
143
     * Get a message used when the value is not valid.
144
     *
145
     * @return string Error message.
146
     *
147
     * @see $message
148
     */
149
    public function getMessage(): string
150
    {
151
        return $this->message;
152
    }
153
154
    public function getOptions(): array
155
    {
156
        return [
157
            'pattern' => $this->getPattern(),
158
            'validSchemes' => $this->validSchemes,
159
            'enableIdn' => $this->enableIdn,
160
            'incorrectInputMessage' => [
161
                'template' => $this->incorrectInputMessage,
162
                'parameters' => [],
163
            ],
164
            'message' => [
165
                'template' => $this->message,
166
                'parameters' => [],
167
            ],
168
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
169
            'skipOnError' => $this->skipOnError,
170
        ];
171
    }
172
173
    public function getHandler(): string
174
    {
175
        return UrlHandler::class;
176
    }
177
}
178