View source
<?php
namespace Drupal\Tests\telephone_validation\Unit;
use Drupal\Core\Locale\CountryManagerInterface;
use Drupal\telephone_validation\Validator;
use Drupal\Tests\UnitTestCase;
use libphonenumber\PhoneNumberFormat;
class ValidatorTest extends UnitTestCase {
protected $countryManager;
protected $validator;
public function setUp() {
parent::setUp();
$mock = $this
->createMock(CountryManagerInterface::class);
$mock
->expects($this
->any())
->method('getList')
->withAnyParameters()
->willReturn([
'NO' => 'Norway',
'CA' => 'Canada',
'US' => 'United States',
]);
$this->countryManager = $mock;
$this->validator = new Validator($this->countryManager);
}
public function testCountryList($countryCode, $label) {
$validator = new Validator($this->countryManager);
$list = $validator
->getCountryList();
self::assertEquals($label, $list[$countryCode]);
}
public function testIsValid($countryCode, $countryPrefix, $number) {
self::assertTrue($this->validator
->isValid($number, PhoneNumberFormat::NATIONAL, [
$countryCode,
]));
self::assertFalse($this->validator
->isValid($number, PhoneNumberFormat::NATIONAL, [
'XYZ',
]));
self::assertFalse($this->validator
->isValid($number, PhoneNumberFormat::NATIONAL, [
'UA',
]));
self::assertFalse($this->validator
->isValid($number, PhoneNumberFormat::INTERNATIONAL, [
$countryCode,
]));
self::assertFalse($this->validator
->isValid($number, PhoneNumberFormat::E164, [
$countryCode,
]));
self::assertTrue($this->validator
->isValid($countryPrefix . $number, PhoneNumberFormat::E164, [
$countryCode,
]));
self::assertTrue($this->validator
->isValid($countryPrefix . $number, PhoneNumberFormat::E164, []));
self::assertFalse($this->validator
->isValid($countryPrefix . $number, PhoneNumberFormat::E164, [
'UA',
]));
}
public function dataCountryList() {
return [
[
'NO',
'Norway - +47',
],
[
'CA',
'Canada - +1',
],
[
'US',
'United States - +1',
],
];
}
public function dataPhoneNumbers() {
return [
[
'CA',
'+1',
'2507638884',
],
[
'NO',
'+47',
'98765432',
],
[
'DK',
'+45',
'55555555',
],
[
'PL',
'+48',
'748111111',
],
];
}
}