default services conflit ?

This commit is contained in:
armansansd
2022-04-27 11:30:43 +02:00
parent 28190a5749
commit 8bb1064a3b
8132 changed files with 900138 additions and 426 deletions

View File

@@ -0,0 +1,68 @@
<?php
namespace CommerceGuys\Addressing\Tests;
use CommerceGuys\Addressing\Subdivision\PatternType;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\AbstractEnum
*/
final class AbstractEnumTest extends TestCase
{
/**
* @covers ::getAll
*/
public function testGetAll()
{
$expectedValues = ['FULL' => 'full', 'START' => 'start'];
$values = PatternType::getAll();
$this->assertEquals($expectedValues, $values);
}
/**
* @covers ::getKey
*/
public function testGetKey()
{
$key = PatternType::getKey('full');
$this->assertEquals('FULL', $key);
$key = PatternType::getKey('invalid');
$this->assertEquals(false, $key);
}
/**
* @covers ::exists
*/
public function testExists()
{
$result = PatternType::exists('start');
$this->assertEquals(true, $result);
$result = PatternType::exists('invalid');
$this->assertEquals(false, $result);
}
/**
* @covers ::assertExists
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage "invalid" is not a valid PatternType value.
*/
public function testAssertExists()
{
$result = PatternType::assertExists('invalid');
}
/**
* @covers ::assertAllExist
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage "invalid" is not a valid PatternType value.
*/
public function testAssertAllExist()
{
$result = PatternType::assertAllExist(['start', 'invalid']);
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace CommerceGuys\Addressing\Tests\AddressFormat;
use CommerceGuys\Addressing\AddressFormat\AddressField;
use CommerceGuys\Addressing\AddressFormat\AddressFormat;
use CommerceGuys\Addressing\AddressFormat\AddressFormatHelper;
use CommerceGuys\Addressing\AddressFormat\FieldOverride;
use CommerceGuys\Addressing\AddressFormat\FieldOverrides;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\AddressFormat\AddressFormatHelper
*/
final class AddressFormatHelperTest extends TestCase
{
/**
* @covers ::getGroupedFields
*/
public function testGetGroupedFields()
{
$format = "%givenName %familyName\n%organization\n%addressLine1\n%addressLine2\n%locality, %postalCode";
$expectedGroupedFields = [
[AddressField::GIVEN_NAME, AddressField::FAMILY_NAME],
[AddressField::ORGANIZATION],
[AddressField::ADDRESS_LINE1],
[AddressField::ADDRESS_LINE2],
[AddressField::LOCALITY, AddressField::POSTAL_CODE],
];
$this->assertEquals($expectedGroupedFields, AddressFormatHelper::getGroupedFields($format));
$fieldOverrides = new FieldOverrides([
AddressField::ORGANIZATION => FieldOverride::HIDDEN,
AddressField::LOCALITY => FieldOverride::HIDDEN,
]);
$expectedGroupedFields = [
[AddressField::GIVEN_NAME, AddressField::FAMILY_NAME],
[AddressField::ADDRESS_LINE1],
[AddressField::ADDRESS_LINE2],
[AddressField::POSTAL_CODE],
];
$this->assertEquals($expectedGroupedFields, AddressFormatHelper::getGroupedFields($format, $fieldOverrides));
}
/**
* @covers ::getRequiredFields
*/
public function testGetRequiredFields()
{
$addressFormat = new AddressFormat([
'country_code' => 'US',
'format' => "%givenName %familyName\n%organization\n%addressLine1\n%addressLine2\n%locality, %administrativeArea %postalCode",
'required_fields' => [
AddressField::ADMINISTRATIVE_AREA,
AddressField::LOCALITY,
AddressField::POSTAL_CODE,
],
]);
$fieldOverrides = new FieldOverrides([]);
$expectedRequiredFields = [
AddressField::ADMINISTRATIVE_AREA,
AddressField::LOCALITY,
AddressField::POSTAL_CODE,
];
$this->assertEquals($expectedRequiredFields, AddressFormatHelper::getRequiredFields($addressFormat, $fieldOverrides));
$fieldOverrides = new FieldOverrides([
AddressField::ADMINISTRATIVE_AREA => FieldOverride::HIDDEN,
AddressField::POSTAL_CODE => FieldOverride::OPTIONAL,
AddressField::ADDRESS_LINE1 => FieldOverride::REQUIRED,
]);
$expectedRequiredFields = [
AddressField::LOCALITY,
AddressField::ADDRESS_LINE1,
];
$this->assertEquals($expectedRequiredFields, AddressFormatHelper::getRequiredFields($addressFormat, $fieldOverrides));
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace CommerceGuys\Addressing\Tests\AddressFormat;
use CommerceGuys\Addressing\AddressFormat\AddressFormat;
use CommerceGuys\Addressing\AddressFormat\AddressFormatRepository;
use CommerceGuys\Addressing\AddressFormat\AdministrativeAreaType;
use CommerceGuys\Addressing\AddressFormat\LocalityType;
use CommerceGuys\Addressing\AddressFormat\PostalCodeType;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\AddressFormat\AddressFormatRepository
*/
final class AddressFormatRepositoryTest extends TestCase
{
/**
* @covers ::get
* @covers ::processDefinition
* @covers ::getGenericDefinition
* @covers ::getDefinitions
*/
public function testGet()
{
$addressFormatRepository = new AddressFormatRepository();
$addressFormat = $addressFormatRepository->get('ES');
// Confirm that the right class has been returned, a known value has
// been successfully populated, and defaults have been merged.
$this->assertInstanceOf(AddressFormat::class, $addressFormat);
$this->assertEquals('ES', $addressFormat->getCountryCode());
$this->assertEquals(AdministrativeAreaType::PROVINCE, $addressFormat->getAdministrativeAreaType());
$this->assertEquals(LocalityType::CITY, $addressFormat->getLocalityType());
$this->assertEquals(PostalCodeType::POSTAL, $addressFormat->getPostalCodeType());
$this->assertEquals('\\d{5}', $addressFormat->getPostalCodePattern());
// Confirm that passing a lowercase country code works.
$anotherAddressFormat = $addressFormatRepository->get('es');
$this->assertSame($anotherAddressFormat, $addressFormat);
}
/**
* @covers ::get
* @covers ::processDefinition
* @covers ::getGenericDefinition
* @covers ::getDefinitions
*/
public function testGetNonExistingAddressFormat()
{
$addressFormatRepository = new AddressFormatRepository();
$addressFormat = $addressFormatRepository->get('ZZ');
$this->assertEquals('ZZ', $addressFormat->getCountryCode());
}
/**
* @covers ::getAll
* @covers ::processDefinition
* @covers ::getGenericDefinition
* @covers ::getDefinitions
*/
public function testGetAll()
{
$addressFormatRepository = new AddressFormatRepository();
$addressFormats = $addressFormatRepository->getAll();
$this->assertArrayHasKey('ES', $addressFormats);
$this->assertArrayHasKey('RS', $addressFormats);
$this->assertEquals('ES', $addressFormats['ES']->getCountryCode());
$this->assertEquals(LocalityType::CITY, $addressFormats['ES']->getLocalityType());
$this->assertEquals('RS', $addressFormats['RS']->getCountryCode());
$this->assertEquals(LocalityType::CITY, $addressFormats['RS']->getLocalityType());
}
}

View File

@@ -0,0 +1,126 @@
<?php
namespace CommerceGuys\Addressing\Tests\AddressFormat;
use CommerceGuys\Addressing\AddressFormat\AddressField;
use CommerceGuys\Addressing\AddressFormat\AddressFormat;
use CommerceGuys\Addressing\AddressFormat\AdministrativeAreaType;
use CommerceGuys\Addressing\AddressFormat\DependentLocalityType;
use CommerceGuys\Addressing\AddressFormat\LocalityType;
use CommerceGuys\Addressing\AddressFormat\PostalCodeType;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\AddressFormat\AddressFormat
*/
final class AddressFormatTest extends TestCase
{
/**
* @covers ::__construct
*
* @expectedException \InvalidArgumentException
*/
public function testMissingProperty()
{
$definition = [
'country_code' => 'US',
];
$addressFormat = new AddressFormat($definition);
}
/**
* @covers ::__construct
*
* @expectedException \InvalidArgumentException
*/
public function testInvalidSubdivision()
{
$definition = [
'country_code' => 'US',
'format' => "%givenName %familyName\n%organization\n%addressLine1\n%addressLine2\n%dependentLocality",
'required_fields' => [AddressField::ADDRESS_LINE1],
'dependent_locality_type' => 'WRONG',
];
$addressFormat = new AddressFormat($definition);
}
/**
* @covers ::__construct
* @covers ::getCountryCode
* @covers ::getLocale
* @covers ::getFormat
* @covers ::getLocalFormat
* @covers ::getUsedFields
* @covers ::getUsedSubdivisionFields
* @covers ::getRequiredFields
* @covers ::getUppercaseFields
* @covers ::getAdministrativeAreaType
* @covers ::getLocalityType
* @covers ::getDependentLocalityType
* @covers ::getPostalCodeType
* @covers ::getPostalCodePattern
* @covers ::getPostalCodePrefix
* @covers ::getSubdivisionDepth
*/
public function testValid()
{
$definition = [
'country_code' => 'US',
'locale' => 'en',
'format' => "%givenName %familyName\n%organization\n%addressLine1\n%addressLine2\n%locality, %administrativeArea %postalCode",
// The local format is made up, US doesn't have one usually.
'local_format' => '%postalCode\n%addressLine1\n%organization\n%givenName %familyName',
'required_fields' => [
AddressField::ADMINISTRATIVE_AREA,
AddressField::LOCALITY,
AddressField::POSTAL_CODE,
AddressField::ADDRESS_LINE1,
],
'uppercase_fields' => [
AddressField::ADMINISTRATIVE_AREA,
AddressField::LOCALITY,
],
'administrative_area_type' => AdministrativeAreaType::STATE,
'locality_type' => LocalityType::CITY,
'dependent_locality_type' => DependentLocalityType::DISTRICT,
'postal_code_type' => PostalCodeType::ZIP,
'postal_code_pattern' => '(\d{5})(?:[ \-](\d{4}))?',
// US doesn't use postal code prefixes, fake one for test purposes.
'postal_code_prefix' => 'US',
'subdivision_depth' => 1,
];
$addressFormat = new AddressFormat($definition);
$this->assertEquals($definition['country_code'], $addressFormat->getCountryCode());
$this->assertEquals($definition['locale'], $addressFormat->getLocale());
$this->assertEquals($definition['format'], $addressFormat->getFormat());
$this->assertEquals($definition['local_format'], $addressFormat->getLocalFormat());
$this->assertEquals($definition['required_fields'], $addressFormat->getRequiredFields());
$this->assertEquals($definition['uppercase_fields'], $addressFormat->getUppercaseFields());
$this->assertEquals($definition['administrative_area_type'], $addressFormat->getAdministrativeAreaType());
$this->assertEquals($definition['locality_type'], $addressFormat->getLocalityType());
// The format has no %dependentLocality, the type must be NULL.
$this->assertNull($addressFormat->getDependentLocalityType());
$this->assertEquals($definition['postal_code_type'], $addressFormat->getPostalCodeType());
$this->assertEquals($definition['postal_code_pattern'], $addressFormat->getPostalCodePattern());
$this->assertEquals($definition['postal_code_prefix'], $addressFormat->getPostalCodePrefix());
$this->assertEquals($definition['subdivision_depth'], $addressFormat->getSubdivisionDepth());
$expectedUsedFields = [
AddressField::ADMINISTRATIVE_AREA,
AddressField::LOCALITY,
AddressField::POSTAL_CODE,
AddressField::ADDRESS_LINE1,
AddressField::ADDRESS_LINE2,
AddressField::ORGANIZATION,
AddressField::GIVEN_NAME,
AddressField::FAMILY_NAME,
];
$this->assertEquals($expectedUsedFields, $addressFormat->getUsedFields());
$expectedUsedSubdivisionFields = [
AddressField::ADMINISTRATIVE_AREA,
AddressField::LOCALITY,
];
$this->assertEquals($expectedUsedSubdivisionFields, $addressFormat->getUsedSubdivisionFields());
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace CommerceGuys\Addressing\Tests\AddressFormat;
use CommerceGuys\Addressing\AddressFormat\AddressField;
use CommerceGuys\Addressing\AddressFormat\FieldOverride;
use CommerceGuys\Addressing\AddressFormat\FieldOverrides;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\AddressFormat\FieldOverrides
*/
final class FieldOverridesTest extends TestCase
{
/**
* @covers ::__construct
*
* @expectedException \InvalidArgumentException
*/
public function testInvalidField()
{
$definition = [
'INVALID_FIELD' => FieldOverride::HIDDEN,
];
$fieldOverrides = new FieldOverrides($definition);
}
/**
* @covers ::__construct
*
* @expectedException \InvalidArgumentException
*/
public function testInvalidOverride()
{
$definition = [
AddressField::POSTAL_CODE => 'INVALID',
];
$fieldOverrides = new FieldOverrides($definition);
}
/**
* @covers ::__construct
*/
public function testEmptyDefinition()
{
$fieldOverrides = new FieldOverrides([]);
$this->assertSame([], $fieldOverrides->getHiddenFields());
$this->assertSame([], $fieldOverrides->getOptionalFields());
$this->assertSame([], $fieldOverrides->getRequiredFields());
}
/**
* @covers ::__construct
* @covers ::getHiddenFields
* @covers ::getOptionalFields
* @covers ::getRequiredFields
*/
public function testOverrides()
{
$fieldOverrides = new FieldOverrides([
AddressField::GIVEN_NAME => FieldOverride::HIDDEN,
AddressField::ADDITIONAL_NAME => FieldOverride::HIDDEN,
AddressField::FAMILY_NAME => FieldOverride::HIDDEN,
AddressField::ORGANIZATION => FieldOverride::REQUIRED,
AddressField::POSTAL_CODE => FieldOverride::OPTIONAL,
]);
$this->assertSame([
AddressField::GIVEN_NAME,
AddressField::ADDITIONAL_NAME,
AddressField::FAMILY_NAME
], $fieldOverrides->getHiddenFields());
$this->assertSame([AddressField::POSTAL_CODE], $fieldOverrides->getOptionalFields());
$this->assertSame([AddressField::ORGANIZATION], $fieldOverrides->getRequiredFields());
}
}

View File

@@ -0,0 +1,164 @@
<?php
namespace CommerceGuys\Addressing\Tests;
use CommerceGuys\Addressing\Address;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Address
*/
final class AddressTest extends TestCase
{
/**
* @covers ::__construct
*/
public function testConstructor()
{
$address = new Address('US', 'CA', 'Mountain View', 'MV', '94043', '94044', '1600 Amphitheatre Parkway', 'Google Bldg 41', 'Google Inc.', 'John', '', 'Smith', 'en');
$this->assertEquals('US', $address->getCountryCode());
$this->assertEquals('CA', $address->getAdministrativeArea());
$this->assertEquals('Mountain View', $address->getLocality());
$this->assertEquals('MV', $address->getDependentLocality());
$this->assertEquals('94043', $address->getPostalCode());
$this->assertEquals('94044', $address->getSortingCode());
$this->assertEquals('1600 Amphitheatre Parkway', $address->getAddressLine1());
$this->assertEquals('Google Bldg 41', $address->getAddressLine2());
$this->assertEquals('Google Inc.', $address->getOrganization());
$this->assertEquals('John', $address->getGivenName());
$this->assertEquals('Smith', $address->getFamilyName());
$this->assertEquals('en', $address->getLocale());
}
/**
* @covers ::getCountryCode
* @covers ::withCountryCode
*/
public function testCountryCode()
{
$address = (new Address())->withCountryCode('US');
$this->assertEquals('US', $address->getCountryCode());
}
/**
* @covers ::getAdministrativeArea
* @covers ::withAdministrativeArea
*/
public function testAdministrativeArea()
{
$address = (new Address())->withAdministrativeArea('CA');
$this->assertEquals('CA', $address->getAdministrativeArea());
}
/**
* @covers ::getLocality
* @covers ::withLocality
*/
public function testLocality()
{
$address = (new Address())->withLocality('Mountain View');
$this->assertEquals('Mountain View', $address->getLocality());
}
/**
* @covers ::getDependentLocality
* @covers ::withDependentLocality
*/
public function testDependentLocality()
{
// US doesn't use dependent localities, so there's no good example here.
$address = (new Address())->withDependentLocality('Mountain View');
$this->assertEquals('Mountain View', $address->getDependentLocality());
}
/**
* @covers ::getPostalCode
* @covers ::withPostalCode
*/
public function testPostalCode()
{
$address = (new Address())->withPostalCode('94043');
$this->assertEquals('94043', $address->getPostalCode());
}
/**
* @covers ::getSortingCode
* @covers ::withSortingCode
*/
public function testSortingCode()
{
// US doesn't use sorting codes, so there's no good example here.
$address = (new Address())->withSortingCode('94043');
$this->assertEquals('94043', $address->getSortingCode());
}
/**
* @covers ::getAddressLine1
* @covers ::withAddressLine1
*/
public function testAddressLine1()
{
$address = (new Address())->withAddressLine1('1600 Amphitheatre Parkway');
$this->assertEquals('1600 Amphitheatre Parkway', $address->getAddressLine1());
}
/**
* @covers ::getAddressLine2
* @covers ::withAddressLine2
*/
public function testAddressLine2()
{
$address = (new Address())->withAddressLine2('Google Bldg 41');
$this->assertEquals('Google Bldg 41', $address->getAddressLine2());
}
/**
* @covers ::getOrganization
* @covers ::withOrganization
*/
public function testOrganization()
{
$address = (new Address())->withOrganization('Google Inc.');
$this->assertEquals('Google Inc.', $address->getOrganization());
}
/**
* @covers ::getGivenName
* @covers ::withGivenName
*/
public function testGivenName()
{
$address = (new Address())->withGivenName('John');
$this->assertEquals('John', $address->getGivenName());
}
/**
* @covers ::getAdditionalName
* @covers ::withAdditionalName
*/
public function testAdditionalName()
{
$address = (new Address())->withAdditionalName('L.');
$this->assertEquals('L.', $address->getAdditionalName());
}
/**
* @covers ::getFamilyName
* @covers ::withFamilyName
*/
public function testFamilyName()
{
$address = (new Address())->withFamilyName('Smith');
$this->assertEquals('Smith', $address->getFamilyName());
}
/**
* @covers ::getLocale
* @covers ::withLocale
*/
public function testLocale()
{
$address = (new Address())->withLocale('en');
$this->assertEquals('en', $address->getLocale());
}
}

View File

@@ -0,0 +1,156 @@
<?php
namespace CommerceGuys\Addressing\Tests\Country;
use CommerceGuys\Addressing\Country\Country;
use CommerceGuys\Addressing\Country\CountryRepository;
use org\bovigo\vfs\vfsStream;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Country\CountryRepository
*/
final class CountryRepositoryTest extends TestCase
{
/**
* Country definitions.
*
* @var array
*/
protected $definitions = [
'en' => [
'FR' => 'France',
'US' => 'United States',
],
'es' => [
'FR' => 'Francia',
'US' => 'Estados Unidos',
],
'de' => [
'FR' => 'Frankreich',
'US' => 'Vereinigte Staaten',
],
];
/**
* @covers ::__construct
*/
public function testConstructor()
{
// Mock the existence of JSON definitions on the filesystem.
$root = vfsStream::setup('resources');
foreach ($this->definitions as $locale => $data) {
vfsStream::newFile('country/' . $locale . '.json')->at($root)->setContent(json_encode($data));
}
// Instantiate the country repository and confirm that the definition path
// was properly set.
$countryRepository = new CountryRepository('de', 'en', 'vfs://resources/country/');
$definitionPath = $this->getObjectAttribute($countryRepository, 'definitionPath');
$this->assertEquals('vfs://resources/country/', $definitionPath);
return $countryRepository;
}
/**
* @covers ::get
* @covers ::loadDefinitions
*
* @uses \CommerceGuys\Addressing\Country\Country
* @uses \CommerceGuys\Addressing\Locale
* @depends testConstructor
*/
public function testGet($countryRepository)
{
// Explicit locale.
$country = $countryRepository->get('FR', 'es');
$this->assertInstanceOf(Country::class, $country);
$this->assertEquals('FR', $country->getCountryCode());
$this->assertEquals('Francia', $country->getName());
$this->assertEquals('FRA', $country->getThreeLetterCode());
$this->assertEquals('250', $country->getNumericCode());
$this->assertEquals('EUR', $country->getCurrencyCode());
$this->assertEquals('es', $country->getLocale());
// Default locale, lowercase country code.
$country = $countryRepository->get('fr');
$this->assertInstanceOf(Country::class, $country);
$this->assertEquals('FR', $country->getCountryCode());
$this->assertEquals('Frankreich', $country->getName());
$this->assertEquals('de', $country->getLocale());
// Fallback locale.
$country = $countryRepository->get('FR', 'INVALID-LOCALE');
$this->assertInstanceOf(Country::class, $country);
$this->assertEquals('FR', $country->getCountryCode());
$this->assertEquals('France', $country->getName());
$this->assertEquals('en', $country->getLocale());
}
/**
* @covers ::get
* @covers ::loadDefinitions
*
* @uses \CommerceGuys\Addressing\Locale
* @expectedException \CommerceGuys\Addressing\Exception\UnknownCountryException
* @depends testConstructor
*/
public function testGetInvalidCountry($countryRepository)
{
$countryRepository->get('INVALID');
}
/**
* @covers ::getAll
* @covers ::loadDefinitions
*
* @uses \CommerceGuys\Addressing\Country\Country
* @uses \CommerceGuys\Addressing\Locale
* @depends testConstructor
*/
public function testGetAll($countryRepository)
{
// Explicit locale.
$countries = $countryRepository->getAll('es');
$this->assertArrayHasKey('FR', $countries);
$this->assertArrayHasKey('US', $countries);
$this->assertEquals('Francia', $countries['FR']->getName());
$this->assertEquals('Estados Unidos', $countries['US']->getName());
// Default locale.
$countries = $countryRepository->getAll();
$this->assertArrayHasKey('FR', $countries);
$this->assertArrayHasKey('US', $countries);
$this->assertEquals('Frankreich', $countries['FR']->getName());
$this->assertEquals('Vereinigte Staaten', $countries['US']->getName());
// Fallback locale.
$countries = $countryRepository->getAll('INVALID-LOCALE');
$this->assertArrayHasKey('FR', $countries);
$this->assertArrayHasKey('US', $countries);
$this->assertEquals('France', $countries['FR']->getName());
$this->assertEquals('United States', $countries['US']->getName());
}
/**
* @covers ::getList
* @covers ::loadDefinitions
*
* @uses \CommerceGuys\Addressing\Locale
* @depends testConstructor
*/
public function testGetList($countryRepository)
{
// Explicit locale.
$list = $countryRepository->getList('es');
$this->assertEquals(['FR' => 'Francia', 'US' => 'Estados Unidos'], $list);
// Default locale.
$list = $countryRepository->getList();
$this->assertEquals(['FR' => 'Frankreich', 'US' => 'Vereinigte Staaten'], $list);
// Fallback locale.
$list = $countryRepository->getList('INVALID-LOCALE');
$this->assertEquals(['FR' => 'France', 'US' => 'United States'], $list);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace CommerceGuys\Addressing\Tests\Country;
use CommerceGuys\Addressing\Country\Country;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Country\Country
*/
final class CountryTest extends TestCase
{
/**
* @covers ::__construct
*/
public function testMissingProperty()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Missing required property "country_code".');
$country = new Country([]);
}
/**
* @covers ::__construct
* @covers ::__toString
* @covers ::getCountryCode
* @covers ::getName
* @covers ::getThreeLetterCode
* @covers ::getNumericCode
* @covers ::getCurrencyCode
* @covers ::getTimezones
* @covers ::getLocale
*/
public function testValid()
{
$definition = [
'country_code' => 'DE',
'name' => 'Allemagne',
'three_letter_code' => 'DEU',
'numeric_code' => '276',
'currency_code' => 'EUR',
'locale' => 'fr',
];
$country = new Country($definition);
$this->assertEquals($definition['country_code'], $country->__toString());
$this->assertEquals($definition['country_code'], $country->getCountryCode());
$this->assertEquals($definition['name'], $country->getName());
$this->assertEquals($definition['three_letter_code'], $country->getThreeLetterCode());
$this->assertEquals($definition['numeric_code'], $country->getNumericCode());
$this->assertEquals($definition['currency_code'], $country->getCurrencyCode());
$this->assertEquals(['Europe/Berlin', 'Europe/Busingen'], $country->getTimezones());
$this->assertEquals($definition['locale'], $country->getLocale());
}
}

View File

@@ -0,0 +1,284 @@
<?php
namespace CommerceGuys\Addressing\Tests\Formatter;
use CommerceGuys\Addressing\Address;
use CommerceGuys\Addressing\AddressFormat\AddressFormatRepository;
use CommerceGuys\Addressing\Country\CountryRepository;
use CommerceGuys\Addressing\Formatter\DefaultFormatter;
use CommerceGuys\Addressing\Subdivision\SubdivisionRepository;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Formatter\DefaultFormatter
*/
final class DefaultFormatterTest extends TestCase
{
/**
* The address format repository.
*
* @var AddressFormatRepositoryInterface
*/
protected $addressFormatRepository;
/**
* The country repository.
*
* @var CountryRepositoryInterface
*/
protected $countryRepository;
/**
* The subdivision repository.
*
* @var SubdivisionRepositoryInterface
*/
protected $subdivisionRepository;
/**
* The formatter.
*
* @var DefaultFormatter
*/
protected $formatter;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->addressFormatRepository = new AddressFormatRepository();
$this->countryRepository = new CountryRepository();
$this->subdivisionRepository = new SubdivisionRepository();
$this->formatter = new DefaultFormatter($this->addressFormatRepository, $this->countryRepository, $this->subdivisionRepository);
}
/**
* @covers ::__construct
*/
public function testConstructor()
{
$formatter = new DefaultFormatter($this->addressFormatRepository, $this->countryRepository, $this->subdivisionRepository);
$this->assertEquals($this->addressFormatRepository, $this->getObjectAttribute($formatter, 'addressFormatRepository'));
$this->assertEquals($this->countryRepository, $this->getObjectAttribute($formatter, 'countryRepository'));
$this->assertEquals($this->subdivisionRepository, $this->getObjectAttribute($formatter, 'subdivisionRepository'));
}
/**
* @covers ::__construct
* @expectedException \InvalidArgumentException
*/
public function testUnrecognizedOption()
{
$formatter = new DefaultFormatter($this->addressFormatRepository, $this->countryRepository, $this->subdivisionRepository, ['unrecognized' => '123']);
}
/**
* @covers ::__construct
* @expectedException \InvalidArgumentException
*/
public function testInvalidOption()
{
$formatter = new DefaultFormatter($this->addressFormatRepository, $this->countryRepository, $this->subdivisionRepository, ['html' => 'INVALID']);
}
/**
* @covers \CommerceGuys\Addressing\Formatter\DefaultFormatter
*/
public function testAndorraAddress()
{
$address = new Address();
$address = $address
->withCountryCode('AD')
->withLocality("Parròquia d'Andorra la Vella")
->withPostalCode('AD500')
->withAddressLine1('C. Prat de la Creu, 62-64');
// Andorra has no predefined administrative areas, but it does have
// predefined localities, which must be shown.
$expectedTextLines = [
'C. Prat de la Creu, 62-64',
"AD500 Parròquia d'Andorra la Vella",
'Andorra',
];
$textAddress = $this->formatter->format($address, ['html' => false]);
$this->assertFormattedAddress($expectedTextLines, $textAddress);
}
/**
* @covers \CommerceGuys\Addressing\Formatter\DefaultFormatter
*/
public function testElSalvadorAddress()
{
$address = new Address();
$address = $address
->withCountryCode('SV')
->withAdministrativeArea('Ahuachapán')
->withLocality('Ahuachapán')
->withAddressLine1('Some Street 12');
$expectedHtmlLines = [
'<p translate="no">',
'<span class="address-line1">Some Street 12</span><br>',
'<span class="locality">Ahuachapán</span><br>',
'<span class="administrative-area">Ahuachapán</span><br>',
'<span class="country">El Salvador</span>',
'</p>',
];
$htmlAddress = $this->formatter->format($address);
$this->assertFormattedAddress($expectedHtmlLines, $htmlAddress);
$expectedTextLines = [
'Some Street 12',
'Ahuachapán',
'Ahuachapán',
'El Salvador',
];
$textAddress = $this->formatter->format($address, ['html' => false]);
$this->assertFormattedAddress($expectedTextLines, $textAddress);
$address = $address->withPostalCode('CP 2101');
$expectedHtmlLines = [
'<p translate="no">',
'<span class="address-line1">Some Street 12</span><br>',
'<span class="postal-code">CP 2101</span>-<span class="locality">Ahuachapán</span><br>',
'<span class="administrative-area">Ahuachapán</span><br>',
'<span class="country">El Salvador</span>',
'</p>',
];
$htmlAddress = $this->formatter->format($address);
$this->assertFormattedAddress($expectedHtmlLines, $htmlAddress);
$expectedTextLines = [
'Some Street 12',
'CP 2101-Ahuachapán',
'Ahuachapán',
'El Salvador',
];
$textAddress = $this->formatter->format($address, ['html' => false]);
$this->assertFormattedAddress($expectedTextLines, $textAddress);
}
/**
* @covers \CommerceGuys\Addressing\Formatter\DefaultFormatter
*/
public function testTaiwanAddress()
{
// Real addresses in the major-to-minor order would be completely in
// Traditional Chinese. That's not the case here, for readability.
$address = new Address();
$address = $address
->withCountryCode('TW')
->withAdministrativeArea('Taipei City')
->withLocality("Da'an District")
->withAddressLine1('Sec. 3 Hsin-yi Rd.')
->withPostalCode('106')
// Any HTML in the fields is supposed to be removed when formatting
// for text, and escaped when formatting for html.
->withOrganization('Giant <h2>Bike</h2> Store')
->withGivenName('Te-Chiang')
->withFamilyName('Liu')
->withLocale('zh-Hant');
$expectedHtmlLines = [
'<p translate="no" class="address postal-address">',
'<span class="country">台灣</span><br>',
'<span class="postal-code">106</span><br>',
'<span class="administrative-area">台北市</span><span class="locality">大安區</span><br>',
'<span class="address-line1">Sec. 3 Hsin-yi Rd.</span><br>',
'<span class="organization">Giant &lt;h2&gt;Bike&lt;/h2&gt; Store</span><br>',
'<span class="family-name">Liu</span> <span class="given-name">Te-Chiang</span>',
'</p>',
];
// Test wrapper attributes and a custom locale.
$htmlAddress = $this->formatter->format($address, [
'locale' => 'zh-Hant',
'html_attributes' => [
'translate' => 'no',
'class' => ['address', 'postal-address'],
],
]);
$this->assertFormattedAddress($expectedHtmlLines, $htmlAddress);
$expectedTextLines = [
'台灣',
'106',
'台北市大安區',
'Sec. 3 Hsin-yi Rd.',
'Giant Bike Store',
'Liu Te-Chiang',
];
$textAddress = $this->formatter->format($address, [
'locale' => 'zh-Hant',
'html' => false,
]);
$this->assertFormattedAddress($expectedTextLines, $textAddress);
}
/**
* @covers \CommerceGuys\Addressing\Formatter\DefaultFormatter
*/
public function testUnitedStatesIncompleteAddress()
{
// Create a US address without a locality.
$address = new Address();
$address = $address
->withCountryCode('US')
->withAdministrativeArea('CA')
->withPostalCode('94043')
->withAddressLine1('1098 Alta Ave');
$expectedHtmlLines = [
'<p translate="no">',
'<span class="address-line1">1098 Alta Ave</span><br>',
'<span class="administrative-area">CA</span> <span class="postal-code">94043</span><br>',
'<span class="country">United States</span>',
'</p>',
];
$htmlAddress = $this->formatter->format($address);
$this->assertFormattedAddress($expectedHtmlLines, $htmlAddress);
$expectedTextLines = [
'1098 Alta Ave',
'CA 94043',
'United States',
];
$textAddress = $this->formatter->format($address, ['html' => false]);
$this->assertFormattedAddress($expectedTextLines, $textAddress);
// Now add the locality, but remove the administrative area.
$address = $address
->withLocality('Mountain View')
->withAdministrativeArea('');
$expectedHtmlLines = [
'<p translate="no">',
'<span class="address-line1">1098 Alta Ave</span><br>',
'<span class="locality">Mountain View</span>, <span class="postal-code">94043</span><br>',
'<span class="country">United States</span>',
'</p>',
];
$htmlAddress = $this->formatter->format($address);
$this->assertFormattedAddress($expectedHtmlLines, $htmlAddress);
$expectedTextLines = [
'1098 Alta Ave',
'Mountain View, 94043',
'United States',
];
$textAddress = $this->formatter->format($address, ['html' => false]);
$this->assertFormattedAddress($expectedTextLines, $textAddress);
}
/**
* Asserts that the formatted address is valid.
*
* @param array $expectedLines
* @param string $formattedAddress
*/
protected function assertFormattedAddress(array $expectedLines, $formattedAddress)
{
$expectedLines = implode("\n", $expectedLines);
$this->assertEquals($expectedLines, $formattedAddress);
}
}

View File

@@ -0,0 +1,179 @@
<?php
namespace CommerceGuys\Addressing\Tests\Formatter;
use CommerceGuys\Addressing\Address;
use CommerceGuys\Addressing\AddressFormat\AddressFormatRepository;
use CommerceGuys\Addressing\Country\CountryRepository;
use CommerceGuys\Addressing\Formatter\PostalLabelFormatter;
use CommerceGuys\Addressing\Subdivision\SubdivisionRepository;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Formatter\PostalLabelFormatter
*/
final class PostalLabelFormatterTest extends TestCase
{
/**
* The address format repository.
*
* @var AddressFormatRepositoryInterface
*/
protected $addressFormatRepository;
/**
* The country repository.
*
* @var CountryRepositoryInterface
*/
protected $countryRepository;
/**
* The subdivision repository.
*
* @var SubdivisionRepositoryInterface
*/
protected $subdivisionRepository;
/**
* The formatter.
*
* @var PostalLabelFormatter
*/
protected $formatter;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->addressFormatRepository = new AddressFormatRepository();
$this->countryRepository = new CountryRepository();
$this->subdivisionRepository = new SubdivisionRepository();
$this->formatter = new PostalLabelFormatter($this->addressFormatRepository, $this->countryRepository, $this->subdivisionRepository);
}
/**
* @covers ::format
*
* @expectedException \InvalidArgumentException
*/
public function testMissingOriginCountryCode()
{
$address = new Address();
$this->formatter->format($address);
}
/**
* @covers \CommerceGuys\Addressing\Formatter\PostalLabelFormatter
*/
public function testEmptyAddress()
{
$expectedLines = [];
$formattedAddress = $this->formatter->format(new Address('US'), ['origin_country' => 'US']);
$this->assertFormattedAddress($expectedLines, $formattedAddress);
}
/**
* @covers \CommerceGuys\Addressing\Formatter\PostalLabelFormatter
*/
public function testUnitedStatesAddress()
{
$address = new Address();
$address = $address
->withCountryCode('US')
->withAdministrativeArea('CA')
->withLocality('Mt View')
->withPostalCode('94043')
->withAddressLine1('1098 Alta Ave');
// Test a US address formatted for sending from the US.
$expectedLines = [
'1098 Alta Ave',
'MT VIEW, CA 94043',
];
$formattedAddress = $this->formatter->format($address, ['origin_country' => 'US']);
$this->assertFormattedAddress($expectedLines, $formattedAddress);
// Test a US address formatted for sending from France.
$expectedLines = [
'1098 Alta Ave',
'MT VIEW, CA 94043',
'ÉTATS-UNIS - UNITED STATES',
];
$formattedAddress = $this->formatter->format($address, [
'locale' => 'fr',
'origin_country' => 'FR',
]);
$this->assertFormattedAddress($expectedLines, $formattedAddress);
}
/**
* @covers \CommerceGuys\Addressing\Formatter\PostalLabelFormatter
*/
public function testJapanAddressShippedFromFrance()
{
$address = new Address();
$address = $address
->withCountryCode('JP')
->withAdministrativeArea('Hokkaido')
->withLocality('Some City')
->withAddressLine1('Address Line 1')
->withAddressLine2('Address Line 2')
->withPostalCode('04')
->withLocale('ja');
// Test a JP address formatted for sending from France.
$expectedLines = [
'JAPON - JAPAN',
'〒04',
'北海道Some City',
'Address Line 1',
'Address Line 2',
];
$formattedAddress = $this->formatter->format($address, [
'locale' => 'fr',
'origin_country' => 'FR',
]);
$this->assertFormattedAddress($expectedLines, $formattedAddress);
}
/**
* @covers \CommerceGuys\Addressing\Formatter\PostalLabelFormatter
*/
public function testAddressLeadingPostPrefix()
{
$address = new Address();
$address = $address
->withCountryCode('CH')
->withLocality('Herrliberg')
->withPostalCode('8047');
// Domestic mail shouldn't have the postal code prefix added.
$expectedLines = [
'8047 Herrliberg',
];
$formattedAddress = $this->formatter->format($address, ['origin_country' => 'CH']);
$this->assertFormattedAddress($expectedLines, $formattedAddress);
// International mail should have the postal code prefix added.
$expectedLines = [
'CH-8047 Herrliberg',
'SWITZERLAND',
];
$formattedAddress = $this->formatter->format($address, ['origin_country' => 'FR']);
$this->assertFormattedAddress($expectedLines, $formattedAddress);
}
/**
* Asserts that the formatted address is valid.
*
* @param array $expectedLines
* @param string $formattedAddress
*/
protected function assertFormattedAddress(array $expectedLines, $formattedAddress)
{
$expectedLines = implode("\n", $expectedLines);
$this->assertEquals($expectedLines, $formattedAddress);
}
}

View File

@@ -0,0 +1,121 @@
<?php
namespace CommerceGuys\Addressing\Tests;
use CommerceGuys\Addressing\Exception\UnknownLocaleException;
use CommerceGuys\Addressing\Locale;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Locale
*/
final class LocaleTest extends TestCase
{
/**
* @covers ::match
*/
public function testMatch()
{
$this->assertTrue(Locale::match('en-US', 'EN_us'));
$this->assertTrue(Locale::match('de', 'de'));
$this->assertFalse(Locale::match('de', 'de-AT'));
$this->assertFalse(Locale::match('de', 'fr'));
}
/**
* @covers ::matchCandidates
*/
public function testMatchCandidates()
{
$this->assertTrue(Locale::matchCandidates('en-US', 'EN_us'));
$this->assertTrue(Locale::matchCandidates('de', 'de'));
$this->assertTrue(Locale::matchCandidates('de', 'de-AT'));
$this->assertFalse(Locale::matchCandidates('de', 'fr'));
// zh-Hant falls back to "root" instead of "zh".
$this->assertFalse(Locale::matchCandidates('zh', 'zh-Hant'));
}
/**
* @covers ::resolve
*/
public function testResolve()
{
$availableLocales = ['bs-Cyrl', 'bs', 'en'];
$locale = Locale::resolve($availableLocales, 'bs-Cyrl-BA');
$this->assertEquals('bs-Cyrl', $locale);
$locale = Locale::resolve($availableLocales, 'bs-Latn-BA');
$this->assertEquals('bs', $locale);
$locale = Locale::resolve($availableLocales, 'de', 'en');
$this->assertEquals('en', $locale);
}
/**
* @covers ::resolve
*/
public function testResolveWithoutResult()
{
$this->expectException(UnknownLocaleException::class);
$availableLocales = ['bs', 'en'];
$locale = Locale::resolve($availableLocales, 'de');
}
/**
* @covers ::canonicalize
*/
public function testCanonicalize()
{
$locale = Locale::canonicalize('BS_cyrl-ba');
$this->assertEquals('bs-Cyrl-BA', $locale);
$locale = Locale::canonicalize(null);
$this->assertEquals(null, $locale);
}
/**
* @covers ::getCandidates
*/
public function testCandidates()
{
$candidates = Locale::getCandidates('en-US');
$this->assertEquals(['en-US', 'en'], $candidates);
$candidates = Locale::getCandidates('en-US', 'en');
$this->assertEquals(['en-US', 'en'], $candidates);
$candidates = Locale::getCandidates('sr', 'en-US');
$this->assertEquals(['sr', 'en-US', 'en'], $candidates);
$candidates = Locale::getCandidates('en-AU');
$this->assertEquals(['en-AU', 'en-001', 'en'], $candidates);
$candidates = Locale::getCandidates('sh');
$this->assertEquals(['sr-Latn'], $candidates);
}
/**
* @covers ::getParent
*/
public function testParent()
{
$this->assertEquals('sr-Latn', Locale::getParent('sr-Latn-RS'));
// sr-Latn falls back to "root" instead of "sr".
$this->assertEquals(null, Locale::getParent('sr-Latn'));
$this->assertEquals(null, Locale::getParent('sr'));
}
/**
* @covers ::replaceAlias
*/
public function testReplaceAlias()
{
$locale = Locale::replaceAlias('zh-CN');
$this->assertEquals('zh-Hans-CN', $locale);
$locale = Locale::replaceAlias(null);
$this->assertEquals(null, $locale);
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace CommerceGuys\Addressing\Tests;
use CommerceGuys\Addressing\PostalCodeHelper;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\PostalCodeHelper
*/
final class PostalCodeHelperTest extends TestCase
{
/**
* @covers ::match
* @covers ::matchRule
* @covers ::buildList
*/
public function testMatch()
{
// Empty rules should pass.
$this->assertEquals(true, PostalCodeHelper::match('123', null, null));
$includeRule = '/(20)[0-9]{1}/';
$excludeRule = '/(20)[0-2]{1}/';
$this->assertEquals(true, PostalCodeHelper::match('203', $includeRule, $excludeRule));
$this->assertEquals(false, PostalCodeHelper::match('202', $includeRule, $excludeRule));
$includeRule = '10, 20, 30:40';
$excludeRule = '35';
$this->assertEquals(true, PostalCodeHelper::match('34', $includeRule, $excludeRule));
$this->assertEquals(false, PostalCodeHelper::match('35', $includeRule, $excludeRule));
$this->assertEquals(true, PostalCodeHelper::match('5', '5:7, 10:20', ''));
$this->assertEquals(true, PostalCodeHelper::match('7', '5:7, 10:20', ''));
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace CommerceGuys\Addressing\Tests\Subdivision;
use CommerceGuys\Addressing\Subdivision\LazySubdivisionCollection;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Subdivision\LazySubdivisionCollection
*/
final class LazySubdivisionCollectionTest extends TestCase
{
/**
* @var LazySubdivisionCollection
*/
protected $collection;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->collection = new LazySubdivisionCollection(['BR', 'Porto Acre']);
}
/**
* @covers ::__construct
*/
public function testConstructor()
{
$collection = new LazySubdivisionCollection(['BR', 'Porto Acre']);
$this->assertEquals(['BR', 'Porto Acre'], $this->getObjectAttribute($collection, 'parents'));
}
/**
* @covers ::doInitialize
*/
public function testInitialize()
{
$subdivision = $this
->getMockBuilder('CommerceGuys\Addressing\Subdivision\Subdivision')
->disableOriginalConstructor()
->getMock();
$subdivisionRepository = $this
->getMockBuilder('CommerceGuys\Addressing\Subdivision\SubdivisionRepository')
->disableOriginalConstructor()
->getMock();
$subdivisionRepository
->expects($this->any())
->method('getAll')
->with(['BR', 'Porto Acre'])
->will($this->returnValue([$subdivision]));
$this->collection->setRepository($subdivisionRepository);
$this->assertFalse($this->collection->isInitialized());
$this->assertCount(1, $this->collection);
$this->assertTrue($this->collection->isInitialized());
}
/**
* @covers ::getRepository
* @covers ::setRepository
*/
public function testRepository()
{
$subdivisionRepository = $this
->getMockBuilder('CommerceGuys\Addressing\Subdivision\SubdivisionRepository')
->disableOriginalConstructor()
->getMock();
$this->collection->setRepository($subdivisionRepository);
$this->assertSame($subdivisionRepository, $this->collection->getRepository());
}
}

View File

@@ -0,0 +1,183 @@
<?php
namespace CommerceGuys\Addressing\Tests\Subdivision;
use CommerceGuys\Addressing\Subdivision\Subdivision;
use CommerceGuys\Addressing\Subdivision\SubdivisionRepository;
use org\bovigo\vfs\vfsStream;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Subdivision\SubdivisionRepository
*/
final class SubdivisionRepositoryTest extends TestCase
{
/**
* Subdivisions.
*
* @var array
*/
protected $subdivisions = [
'BR' => [
'country_code' => 'BR',
'locale' => 'pt',
'subdivisions' => [
'SC' => [
'name' => 'Santa Catarina',
'iso_code' => 'BR-SC',
'postal_code_pattern' => '8[89]',
'postal_code_pattern_type' => 'full',
'has_children' => true,
],
'SP' => [
'name' => 'São Paulo',
'iso_code' => 'BR-SP',
'postal_code_pattern' => '[01][1-9]',
'has_children' => true,
],
],
],
'BR-249a39f10ac434b1fcd4d51516266b8e' => [
'country_code' => 'BR',
'parents' => ['BR', 'SC'],
'locale' => 'pt',
'subdivisions' => [
'Abelardo Luz' => [],
],
],
'BR-8ef7a36db3f5d47d46566f851be5f610' => [
'country_code' => 'BR',
'parents' => ['BR', 'SP'],
'locale' => 'pt',
'subdivisions' => [
'Anhumas' => [],
]
],
];
/**
* @covers ::__construct
*/
public function testConstructor()
{
// Mock the existence of JSON definitions on the filesystem.
$root = vfsStream::setup('resources');
$directory = vfsStream::newDirectory('subdivision')->at($root);
foreach ($this->subdivisions as $parent => $data) {
$filename = $parent . '.json';
vfsStream::newFile($filename)->at($directory)->setContent(json_encode($data));
}
// Instantiate the subdivision repository and confirm that the
// definition path was properly set.
$subdivisionRepository = new SubdivisionRepository(null, 'vfs://resources/subdivision/');
$definitionPath = $this->getObjectAttribute($subdivisionRepository, 'definitionPath');
$this->assertEquals('vfs://resources/subdivision/', $definitionPath);
return $subdivisionRepository;
}
/**
* @covers ::get
* @covers ::hasData
* @covers ::loadDefinitions
* @covers ::processDefinitions
* @covers ::buildGroup
* @covers ::createSubdivisionFromDefinitions
*
* @depends testConstructor
*/
public function testGet($subdivisionRepository)
{
$subdivision = $subdivisionRepository->get('SC', ['BR']);
$subdivisionChild = $subdivisionRepository->get('Abelardo Luz', ['BR', 'SC']);
$this->assertInstanceOf(Subdivision::class, $subdivision);
$this->assertEquals(null, $subdivision->getParent());
$this->assertEquals('BR', $subdivision->getCountryCode());
$this->assertEquals('pt', $subdivision->getLocale());
$this->assertEquals('SC', $subdivision->getCode());
$this->assertEquals('Santa Catarina', $subdivision->getName());
$this->assertEquals('BR-SC', $subdivision->getIsoCode());
$this->assertEquals('8[89]', $subdivision->getPostalCodePattern());
$this->assertEquals('full', $subdivision->getPostalCodePatternType());
$children = $subdivision->getChildren();
$this->assertEquals($subdivisionChild, $children['Abelardo Luz']);
$this->assertInstanceOf(Subdivision::class, $subdivisionChild);
$this->assertEquals('Abelardo Luz', $subdivisionChild->getCode());
// $subdivision contains the loaded children while $parent doesn't,
// so they can't be compared directly.
$parent = $subdivisionChild->getParent();
$this->assertInstanceOf(Subdivision::class, $parent);
$this->assertEquals($subdivision->getCode(), $parent->getCode());
}
/**
* @covers ::get
* @covers ::hasData
* @covers ::loadDefinitions
* @covers ::processDefinitions
* @covers ::buildGroup
* @covers ::createSubdivisionFromDefinitions
*
* @depends testConstructor
*/
public function testGetInvalidSubdivision($subdivisionRepository)
{
$subdivision = $subdivisionRepository->get('FAKE', ['BR']);
$this->assertNull($subdivision);
}
/**
* @covers ::getAll
* @covers ::hasData
* @covers ::loadDefinitions
* @covers ::processDefinitions
* @covers ::buildGroup
* @covers ::createSubdivisionFromDefinitions
*
* @depends testConstructor
*/
public function testGetAll($subdivisionRepository)
{
$subdivisions = $subdivisionRepository->getAll(['RS']);
$this->assertEquals([], $subdivisions);
$subdivisions = $subdivisionRepository->getAll(['BR']);
$this->assertCount(2, $subdivisions);
$this->assertArrayHasKey('SC', $subdivisions);
$this->assertArrayHasKey('SP', $subdivisions);
$this->assertEquals($subdivisions['SC']->getCode(), 'SC');
$this->assertEquals($subdivisions['SP']->getCode(), 'SP');
$subdivisions = $subdivisionRepository->getAll(['BR', 'SC']);
$this->assertCount(1, $subdivisions);
$this->assertArrayHasKey('Abelardo Luz', $subdivisions);
$this->assertEquals($subdivisions['Abelardo Luz']->getCode(), 'Abelardo Luz');
}
/**
* @covers ::getList
* @covers ::hasData
* @covers ::loadDefinitions
* @covers ::processDefinitions
* @covers ::buildGroup
*
* @depends testConstructor
*/
public function testGetList($subdivisionRepository)
{
$list = $subdivisionRepository->getList(['RS']);
$this->assertEquals([], $list);
$list = $subdivisionRepository->getList(['BR']);
$expectedList = ['SC' => 'Santa Catarina', 'SP' => 'São Paulo'];
$this->assertEquals($expectedList, $list);
$list = $subdivisionRepository->getList(['BR', 'SC']);
$expectedList = ['Abelardo Luz' => 'Abelardo Luz'];
$this->assertEquals($expectedList, $list);
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace CommerceGuys\Addressing\Tests\Subdivision;
use CommerceGuys\Addressing\Subdivision\PatternType;
use CommerceGuys\Addressing\Subdivision\Subdivision;
use Doctrine\Common\Collections\ArrayCollection;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Subdivision\Subdivision
*/
final class SubdivisionTest extends TestCase
{
/**
* @covers ::__construct
*
* @expectedException \InvalidArgumentException
*/
public function testMissingProperty()
{
$definition = [
'country_code' => 'US',
];
$subdivision = new Subdivision($definition);
}
/**
* @covers ::__construct
* @covers ::getParent
* @covers ::getCountryCode
* @covers ::getLocale
* @covers ::getCode
* @covers ::getLocalCode
* @covers ::getName
* @covers ::getLocalName
* @covers ::getIsoCode
* @covers ::getPostalCodePattern
* @covers ::getPostalCodePatternType
* @covers ::getChildren
* @covers ::hasChildren
*/
public function testValid()
{
$mockBuilder = $this->getMockBuilder('CommerceGuys\Addressing\Subdivision\Subdivision');
$mockBuilder = $mockBuilder->disableOriginalConstructor();
$parent = $mockBuilder->getMock();
$children = new ArrayCollection([$mockBuilder->getMock(), $mockBuilder->getMock()]);
$definition = [
'parent' => $parent,
'country_code' => 'US',
'locale' => 'en',
'code' => 'CA',
'local_code' => 'CA!',
'name' => 'California',
'local_name' => 'California!',
'iso_code' => 'US-CA',
'postal_code_pattern' => '9[0-5]|96[01]',
'postal_code_pattern_type' => PatternType::START,
'children' => $children,
];
$subdivision = new Subdivision($definition);
$this->assertEquals($definition['parent'], $subdivision->getParent());
$this->assertEquals($definition['country_code'], $subdivision->getCountryCode());
$this->assertEquals($definition['locale'], $subdivision->getLocale());
$this->assertEquals($definition['code'], $subdivision->getCode());
$this->assertEquals($definition['local_code'], $subdivision->getLocalCode());
$this->assertEquals($definition['name'], $subdivision->getName());
$this->assertEquals($definition['local_name'], $subdivision->getLocalName());
$this->assertEquals($definition['iso_code'], $subdivision->getIsoCode());
$this->assertEquals($definition['postal_code_pattern'], $subdivision->getPostalCodePattern());
$this->assertEquals($definition['postal_code_pattern_type'], $subdivision->getPostalCodePatternType());
$this->assertEquals($definition['children'], $subdivision->getChildren());
$this->assertTrue($subdivision->hasChildren());
}
}

View File

@@ -0,0 +1,41 @@
<?php
namespace CommerceGuys\Addressing\Tests;
use CommerceGuys\Addressing\UpdateHelper;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\UpdateHelper
*/
final class UpdateHelperTest extends TestCase
{
/**
* @covers ::splitRecipient
*/
public function testSplitRecipient()
{
$expectedName = ['givenName' => 'Erzsébet', 'familyName' => 'Báthory'];
$this->assertEquals($expectedName, UpdateHelper::splitRecipient('Báthory Erzsébet', 'HU'));
$expectedName = ['givenName' => 'Matt', 'familyName' => 'Glaman'];
$this->assertEquals($expectedName, UpdateHelper::splitRecipient('Matt Glaman', 'US'));
}
/**
* @covers ::updateSubdivision
* @covers ::loadSubdivisionUpdateMap
*/
public function testUpdateSubdivision()
{
// No predefined subdivisions.
$this->assertEquals('RS-RS', UpdateHelper::updateSubdivision('RS-RS'));
// No dash.
$this->assertEquals('California', UpdateHelper::updateSubdivision('California'));
// Simple conversion.
$this->assertEquals('CA', UpdateHelper::updateSubdivision('US-CA'));
// Mapping.
$this->assertEquals('Hokkaido', UpdateHelper::updateSubdivision('JP-01'));
// Unknown.
$this->assertEquals('JP-CA', UpdateHelper::updateSubdivision('JP-CA'));
}
}

View File

@@ -0,0 +1,522 @@
<?php
namespace CommerceGuys\Addressing\Tests\Validator\Constraints;
use CommerceGuys\Addressing\Address;
use CommerceGuys\Addressing\AddressFormat\AddressField;
use CommerceGuys\Addressing\AddressFormat\FieldOverride;
use CommerceGuys\Addressing\AddressFormat\FieldOverrides;
use CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraint;
use CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
final class AddressFormatConstraintValidatorTest extends ConstraintValidatorTestCase
{
/**
* @var AddressFormatConstraint
*/
protected $constraint;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->constraint = new AddressFormatConstraint();
// The following code is copied from the parent setUp(), which isn't
// called to avoid the call to \Locale, which introduces a dependency
// on the intl extension (or symfony/intl).
$this->group = 'MyGroup';
$this->metadata = null;
$this->object = null;
$this->value = 'InvalidValue';
$this->root = 'root';
$this->propertyPath = '';
$this->context = $this->createContext();
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
}
protected function createValidator()
{
return new AddressFormatConstraintValidator();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testInvalidValueType()
{
$this->validator->validate(new \stdClass(), $this->constraint);
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testEmptyIsValid()
{
$this->validator->validate(new Address(), $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testAndorraOK()
{
$address = new Address();
$address = $address
->withCountryCode('AD')
->withLocality("Parròquia d'Andorra la Vella")
->withPostalCode('AD500')
->withAddressLine1('C. Prat de la Creu, 62-64')
->withGivenName('Antoni')
->withFamilyName('Martí');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testAndorraNotOK()
{
// Andorra has no predefined administrative areas, but it does have
// predefined localities, which must be validated.
$address = new Address();
$address = $address
->withCountryCode('AD')
->withLocality('INVALID')
->withPostalCode('AD500')
->withAddressLine1('C. Prat de la Creu, 62-64')
->withGivenName('Antoni')
->withFamilyName('Martí');
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->invalidMessage)
->atPath('[locality]')
->setInvalidValue('INVALID')
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testUnitedStatesOK()
{
$address = new Address();
$address = $address
->withCountryCode('US')
->withAdministrativeArea('CA')
->withLocality('Mountain View')
->withPostalCode('94043')
->withAddressLine1('1098 Alta Ave')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testUnitedStatesNotOK()
{
$address = new Address();
$address = $address
->withCountryCode('US')
->withAdministrativeArea('CA')
// Fails the format-level check.
->withPostalCode('909')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->notBlankMessage)
->atPath('[addressLine1]')
->setInvalidValue(null)
->buildNextViolation($this->constraint->notBlankMessage)
->atPath('[locality]')
->setInvalidValue(null)
->buildNextViolation($this->constraint->invalidMessage)
->atPath('[postalCode]')
->setInvalidValue('909')
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testUnitedStatesSubdivisionPostcodePattern()
{
// Test with subdivision-level postal code validation disabled.
$this->constraint->extendedPostalCodeValidation = false;
$address = new Address();
$address = $address
->withCountryCode('US')
->withAdministrativeArea('CA')
->withLocality('Mountain View')
->withAddressLine1('1098 Alta Ave')
// Satisfies the format-level check, fails the subdivision-level one.
->withPostalCode('84025')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
// Now test with the subdivision-level postal code validation enabled.
$this->constraint->extendedPostalCodeValidation = true;
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->invalidMessage)
->atPath('[postalCode]')
->setInvalidValue('84025')
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testChinaOK()
{
$address = new Address();
$address = $address
->withCountryCode('CN')
->withAdministrativeArea('Beijing Shi')
->withLocality('Xicheng Qu')
->withPostalCode('123456')
->withAddressLine1('Yitiao Lu')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testGermanAddress()
{
$address = new Address();
$address = $address
->withCountryCode('DE')
->withLocality('Berlin')
->withPostalCode('10553')
->withAddressLine1('Huttenstr. 50')
->withOrganization('BMW AG Niederkassung Berlin')
->withGivenName('Dieter')
->withFamilyName('Diefendorf');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
// Testing with a empty city should fail.
$address = $address->withLocality(null);
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->notBlankMessage)
->atPath('[locality]')
->setInvalidValue(null)
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testIrishAddress()
{
$address = new Address();
$address = $address
->withCountryCode('IE')
->withAdministrativeArea('Co. Donegal')
->withLocality('Dublin')
->withAddressLine1('7424 118 Avenue NW')
->withGivenName('Conan')
->withFamilyName("O'Brien");
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
// Test the same address but leave the county empty. This address should be valid
// since county is not required.
$address = $address->withAdministrativeArea(null);
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testChinaPostalCodeBadFormat()
{
$address = new Address();
$address = $address
->withCountryCode('CN')
->withAdministrativeArea('Beijing Shi')
->withLocality('Xicheng Qu')
->withPostalCode('InvalidValue')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->notBlankMessage)
->atPath('[addressLine1]')
->setInvalidValue(null)
->buildNextViolation($this->constraint->invalidMessage)
->atPath('[postalCode]')
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testEmptyPostalCodeReportedAsGoodFormat()
{
$address = new Address();
$address = $address
->withCountryCode('CL')
->withAdministrativeArea('Antofagasta')
->withLocality('San Pedro de Atacama')
->withPostalCode('')
->withAddressLine1('GUSTAVO LE PAIGE ST #159')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
// Now check for US addresses, which require a postal code. The following
// address's postal code is wrong because it is missing a required field, not
// because it doesn't match the expected postal code pattern.
$address = new Address();
$address = $address
->withCountryCode('US')
->withAdministrativeArea('CA')
->withLocality('California')
->withAddressLine1('1098 Alta Ave')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->notBlankMessage)
->atPath('[postalCode]')
->setInvalidValue(null)
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testChinaTaiwanOk()
{
$address = new Address();
$address = $address
->withCountryCode('CN')
->withAdministrativeArea('Taiwan')
->withLocality('Taichung City')
->withDependentLocality('Xitun District')
->withPostalCode('407')
->withAddressLine1('12345 Yitiao Lu')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testChinaTaiwanUnknownDistrict()
{
$address = new Address();
$address = $address
->withCountryCode('CN')
->withAdministrativeArea('Taiwan')
->withLocality('Taichung City')
->withDependentLocality('InvalidValue')
->withPostalCode('407')
->withAddressLine1('12345 Yitiao Lu')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->invalidMessage)
->atPath('[dependentLocality]')
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testStreetVerification()
{
$address = new Address();
$address = $address
->withCountryCode('US')
->withAdministrativeArea('CA')
->withLocality('Mountain View')
->withPostalCode('94043')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->notBlankMessage)
->atPath('[addressLine1]')
->setInvalidValue(null)
->assertRaised();
}
/**
* @covers CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testJapan()
{
$address = new Address();
$address = $address
->withCountryCode('JP')
->withAdministrativeArea('Kyoto')
->withLocality('Shigeru Miyamoto')
->withPostalCode('601-8501')
->withAddressLine1('11-1 Kamitoba-hokotate-cho')
->withGivenName('John')
->withFamilyName('Smith');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testCanadaMixedCasePostcode()
{
$address = new Address();
$address = $address
->withCountryCode('CA')
->withAdministrativeArea('QC')
->withLocality('Montreal')
->withPostalCode('H2b 2y5')
->withAddressLine1('11 East St')
->withGivenName('Joe')
->withFamilyName('Bloggs');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testCanadaUnusedFields()
{
$address = new Address();
$address = $address
->withCountryCode('CA')
->withAdministrativeArea('QC')
->withLocality('Montreal')
->withPostalCode('H2b 2y5')
->withSortingCode('InvalidValue')
->withAddressLine1('11 East St')
->withGivenName('Joe')
->withFamilyName('Bloggs');
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->blankMessage)
->atPath('[sortingCode]')
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testOverriddenRequiredFields()
{
// Confirm that it is possible to omit required name fields.
// Intentionally uses the deprecated fields setting to confirm
// that the BC layer works.
$nameFields = [AddressField::GIVEN_NAME, AddressField::FAMILY_NAME];
$this->constraint = new AddressFormatConstraint([
'fields' => array_diff(AddressField::getAll(), $nameFields),
]);
$address = new Address();
$address = $address
->withCountryCode('CN')
->withAdministrativeArea('Beijing Shi')
->withLocality('Xicheng Qu')
->withPostalCode('123456')
->withAddressLine1('Yitiao Lu');
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
// Confirm that an optional override works the same way.
$this->constraint->fields = [];
$this->constraint->fieldOverrides = new FieldOverrides([
AddressField::GIVEN_NAME => FieldOverride::OPTIONAL,
AddressField::FAMILY_NAME => FieldOverride::OPTIONAL,
]);
$this->validator->validate($address, $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testHiddenPostalCodeField()
{
// Confirm that postal code validation is skipped.
$this->constraint->fieldOverrides = new FieldOverrides([
AddressField::POSTAL_CODE => FieldOverride::HIDDEN,
]);
$address = new Address();
$address = $address
->withCountryCode('CN')
->withAdministrativeArea('Beijing Shi')
->withLocality('Xicheng Qu')
->withAddressLine1('Yitiao Lu')
->withGivenName('John')
->withFamilyName('Smith')
->withPostalCode('INVALID');
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->blankMessage)
->atPath('[postalCode]')
->setInvalidValue('INVALID')
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\AddressFormatConstraintValidator
*/
public function testHiddenSubdivisionField()
{
// Confirm that subdivision validation is skipped.
$this->constraint->fieldOverrides = new FieldOverrides([
AddressField::ADMINISTRATIVE_AREA => FieldOverride::HIDDEN,
]);
$address = new Address();
$address = $address
->withCountryCode('CN')
->withLocality('Xicheng Qu')
->withPostalCode('123456')
->withAddressLine1('Yitiao Lu')
->withGivenName('John')
->withFamilyName('Smith')
->withAdministrativeArea('INVALID');
$this->validator->validate($address, $this->constraint);
$this->buildViolation($this->constraint->blankMessage)
->atPath('[administrativeArea]')
->setInvalidValue('INVALID')
->assertRaised();
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace CommerceGuys\Addressing\Tests\Validator\Constraints;
use CommerceGuys\Addressing\Validator\Constraints\CountryConstraint;
use CommerceGuys\Addressing\Validator\Constraints\CountryConstraintValidator;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Validator\Constraints\CountryConstraintValidator
*/
final class CountryConstraintValidatorTest extends ConstraintValidatorTestCase
{
/**
* @var CountryConstraint
*/
protected $constraint;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->constraint = new CountryConstraint();
// The following code is copied from the parent setUp(), which isn't
// called to avoid the call to \Locale, which introduces a dependency
// on the intl extension (or symfony/intl).
$this->group = 'MyGroup';
$this->metadata = null;
$this->object = null;
$this->value = 'InvalidValue';
$this->root = 'root';
$this->propertyPath = '';
$this->context = $this->createContext();
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
}
protected function createValidator()
{
return new CountryConstraintValidator();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\CountryConstraintValidator
*/
public function testEmptyIsValid()
{
$this->validator->validate(null, $this->constraint);
$this->assertNoViolation();
$this->validator->validate('', $this->constraint);
$this->assertNoViolation();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\CountryConstraintValidator
*
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testInvalidValueType()
{
$this->validator->validate(new \stdClass(), $this->constraint);
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\CountryConstraintValidator
*/
public function testInvalidCountry()
{
$this->validator->validate('InvalidValue', $this->constraint);
$this->buildViolation($this->constraint->message)
->setParameters(['{{ value }}' => '"InvalidValue"'])
->atPath('')
->assertRaised();
}
/**
* @covers \CommerceGuys\Addressing\Validator\Constraints\CountryConstraintValidator
*
* @dataProvider getValidCountries
*/
public function testValidCountries($country)
{
$this->validator->validate($country, $this->constraint);
$this->assertNoViolation();
}
public function getValidCountries()
{
return [
['GB'],
['AT'],
['MY'],
];
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace CommerceGuys\Addressing\Tests\Zone;
use CommerceGuys\Addressing\Address;
use CommerceGuys\Addressing\Zone\ZoneTerritory;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Zone\ZoneTerritory
*/
final class ZoneTerritoryTest extends TestCase
{
/**
* @covers ::__construct
*
* @expectedException \InvalidArgumentException
*/
public function testMissingProperty()
{
$territory = new ZoneTerritory([]);
}
/**
* @covers ::__construct
* @covers ::getCountryCode
* @covers ::getAdministrativeArea
* @covers ::getLocality
* @covers ::getDependentLocality
* @covers ::getIncludedPostalCodes
* @covers ::getExcludedPostalCodes
* @covers ::match
*/
public function testValid()
{
$definition = [
'country_code' => 'BR',
'administrative_area' => 'RJ',
'locality' => 'Areal',
'dependent_locality' => 'Random',
'included_postal_codes' => '123456',
'excluded_postal_codes' => '789',
];
$territory = new ZoneTerritory($definition);
$this->assertEquals($definition['country_code'], $territory->getCountryCode());
$this->assertEquals($definition['administrative_area'], $territory->getAdministrativeArea());
$this->assertEquals($definition['locality'], $territory->getLocality());
$this->assertEquals($definition['dependent_locality'], $territory->getDependentLocality());
$this->assertEquals($definition['included_postal_codes'], $territory->getIncludedPostalCodes());
$this->assertEquals($definition['excluded_postal_codes'], $territory->getExcludedPostalCodes());
$brazilian_address = new Address('BR', 'RJ', 'Areal', 'Random', '123456');
$serbian_address = new Address('RS');
$this->assertTrue($territory->match($brazilian_address));
$this->assertFalse($territory->match($serbian_address));
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace CommerceGuys\Addressing\Tests\Zone;
use CommerceGuys\Addressing\Address;
use CommerceGuys\Addressing\Zone\Zone;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass \CommerceGuys\Addressing\Zone\Zone
*/
final class ZoneTest extends TestCase
{
/**
* @covers ::__construct
*
* @expectedException \InvalidArgumentException
*/
public function testMissingProperty()
{
$definition = [
'id' => 'test',
];
$zone = new Zone($definition);
}
/**
* @covers ::__construct
*
* @expectedException \InvalidArgumentException
*/
public function testInvalidTerritories()
{
$definition = [
'id' => 'test',
'label' => 'Test',
'territories' => 'WRONG',
];
$zone = new Zone($definition);
}
/**
* @covers ::__construct
* @covers ::getId
* @covers ::getLabel
* @covers ::getTerritories
* @covers ::match
*/
public function testValid()
{
$definition = [
'id' => 'de_fr',
'label' => 'Germany and France',
'territories' => [
['country_code' => 'DE'],
['country_code' => 'FR'],
],
];
$zone = new Zone($definition);
$this->assertEquals($definition['id'], $zone->getId());
$this->assertEquals($definition['label'], $zone->getLabel());
$this->assertCount(2, $zone->getTerritories());
$this->assertEquals($definition['territories'][0]['country_code'], $zone->getTerritories()[0]->getCountryCode());
$this->assertEquals($definition['territories'][1]['country_code'], $zone->getTerritories()[1]->getCountryCode());
$german_address = new Address('DE');
$serbian_address = new Address('RS');
$this->assertTrue($zone->match($german_address));
$this->assertFalse($zone->match($serbian_address));
}
}