Skip to main content

PhoneMapper

Maps an input value to a normalized phone string (or null).

Accepts the following input types:

  • string.
  • Any Stringable object.
  • null — left as null, subject to validation.

Non-null values are normalized before validation: StringUtils::clean() trims and collapses whitespace, a leading 00 is replaced with +, the space after a + is removed, and parentheses are stripped — except the (0) optional-trunk prefix after a country code, which is kept.

Validation possibilities​

ParameterTypeDefaultDescription
$mandatoryboolfalseRejects null input.

Phone format validation is always applied, regardless of $mandatory.

Example: basic normalization​

$result = Bind::values(' +41 (0) 52 233 79 77 ', null)->map(Mappers::phone())->toArray()->exec();
var_dump($result->get());

Output:

array(2) {
[0]=>
string(20) "+41 (0) 52 233 79 77"
[1]=>
NULL
}

Example: mandatory and invalid format​

$result = Bind::attrs(['phone1' => '+ 41! 12 123 45 67a', 'phone2' => 'äöl@äsdf.adsf', 'phone3' => null])
->props(['phone1', 'phone2', 'phone3'], Mappers::phone(true))
->toArray()
->exec();

// result will be invalid with error messages provided for all phone properties.
var_dump($result->isValid()); // false
var_dump($result->getErrorMap()->getChild('phone1')->isEmpty()); // false due to invalid format
var_dump($result->getErrorMap()->getChild('phone2')->isEmpty()); // false due to invalid format
var_dump($result->getErrorMap()->getChild('phone3')->isEmpty()); // false because mandatory