UrlMapper
Maps an input value to a n2n\util\uri\Url object (or null).
Accepts the following input types:
string.- Any
Stringableobject. null— left asnull, subject to validation.
Non-null values are cleaned with StringUtils::clean() and parsed with Url::create(). If parsing fails, a validation error is recorded and the value is set to null.
Validation possibilities
| Parameter | Type | Default | Description |
|---|---|---|---|
| $mandatory | bool | false | Rejects null input. |
| $allowedSchemas | ?array | ['https', 'http'] | Restricts the URL scheme to this list; null allows any scheme. |
| $schemeRequired | bool | true | Requires a scheme to be present. |
| $maxLength | int | 2048 | Rejects URLs longer than this many characters. |
URL format validation is always applied, regardless of $mandatory.
Example: basic conversion
$result = Bind::values('https://example.com', null)->map(Mappers::url())->toArray()->exec();
var_dump($result->get());
Output:
array(2) {
[0]=>
object(n2n\util\uri\Url)#1 (5) {
["scheme":"n2n\util\uri\Url":private]=>
string(5) "https"
["authority":"n2n\util\uri\Url":private]=>
object(n2n\util\uri\Authority)#2 (4) {
["user":"n2n\util\uri\Authority":private]=>
NULL
["password":"n2n\util\uri\Authority":private]=>
NULL
["host":"n2n\util\uri\Authority":private]=>
string(11) "example.com"
["port":"n2n\util\uri\Authority":private]=>
NULL
}
["path":"n2n\util\uri\Url":private]=>
NULL
["query":"n2n\util\uri\Url":private]=>
NULL
["fragment":"n2n\util\uri\Url":private]=>
NULL
}
[1]=>
NULL
}
Example: mandatory, invalid format and disallowed scheme
$result = Bind::attrs(['url1' => 'invalid-url', 'url2' => 'ftp://example.com', 'url3' => null])
->props(['url1', 'url2', 'url3'], Mappers::url(true))
->toArray()
->exec();
// result will be invalid with error messages provided for all url properties.
var_dump($result->isValid()); // false
var_dump($result->getErrorMap()->getChild('url1')->isEmpty()); // false due to invalid format
var_dump($result->getErrorMap()->getChild('url2')->isEmpty()); // false due to disallowed scheme
var_dump($result->getErrorMap()->getChild('url3')->isEmpty()); // false because mandatory