Passed
Pull Request — master (#332)
by Dmitriy
02:45
created

Url::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 36
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 36
ccs 3
cts 3
cp 1
rs 10
cc 3
nc 2
nop 7
crap 3
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\RuleNameTrait;
11
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait;
12
use Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait;
13
use Yiisoft\Validator\Rule\Trait\WhenTrait;
14
use Yiisoft\Validator\SerializableRuleInterface;
15
use Yiisoft\Validator\SkipOnEmptyInterface;
16
use Yiisoft\Validator\SkipOnErrorInterface;
17
use Yiisoft\Validator\ValidationContext;
18
use Yiisoft\Validator\WhenInterface;
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 part are correct.
24
 * It does not check the remaining parts of a URL.
25
 */
26
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
27
final class Url implements SerializableRuleInterface, SkipOnErrorInterface, WhenInterface, SkipOnEmptyInterface
28
{
29
    use RuleNameTrait;
30
    use SkipOnEmptyTrait;
31
    use SkipOnErrorTrait;
32
    use WhenTrait;
33
34 3
    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 3
        if ($enableIDN && !function_exists('idn_to_ascii')) {
69 1
            throw new RuntimeException('In order to use IDN validation intl extension must be installed and enabled.');
70
        }
71
    }
72
73 41
    public function getPattern(): string
74
    {
75 41
        if (str_contains($this->pattern, '{schemes}')) {
76 38
            return str_replace('{schemes}', '((?i)' . implode('|', $this->validSchemes) . ')', $this->pattern);
77
        }
78
79 3
        return $this->pattern;
80
    }
81
82
    /**
83
     * @return array|string[]
84
     */
85
    public function getValidSchemes(): array
86
    {
87
        return $this->validSchemes;
88
    }
89
90 38
    public function isEnableIDN(): bool
91
    {
92 38
        return $this->enableIDN;
93
    }
94
95 16
    public function getMessage(): string
96
    {
97 16
        return $this->message;
98
    }
99
100 4
    public function getOptions(): array
101
    {
102
        return [
103 4
            'pattern' => $this->getPattern(),
104 4
            'validSchemes' => $this->validSchemes,
105 4
            'enableIDN' => $this->enableIDN,
106
            'message' => [
107 4
                'message' => $this->message,
108
            ],
109 4
            'skipOnEmpty' => $this->getSkipOnEmptyOption(),
110 4
            'skipOnError' => $this->skipOnError,
111
        ];
112
    }
113
114 1
    public function getHandlerClassName(): string
115
    {
116 1
        return UrlHandler::class;
117
    }
118
}
119