respect-validation/library/Rules/SubdivisionCode.php
Henrique Moody 9c9c76ebfb
Use "sokil/php-isocodes" on SubdivisionCode
Inside the "data/" directory, we have files with lists of subdivisions
that need to be updated. We have to update them manually, or we automate
that task with a script and GitHub actions.

The two options are very time consuming and also not ideal. We don't
want to deal with that problem and, thinking that the user of this
library may want to show the data that we validate, we should create a
whole library to make it more usable.

The "sokil/php-isocodes" is a simple library that, even supports
translations. It's frequently updated and has gone to major performance
updates.

I am not fond of the idea of requiring an external library to install
Validation, as I have seen that gone wrong before [1]. Ideally, that
would be an optional dependency for people who would like to use those
rules, but to make that happen, we need to release a MAJOR version.

[1]: d072b4de6a

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2021-02-06 15:09:04 +01:00

74 lines
1.7 KiB
PHP

<?php
/*
* This file is part of Respect/Validation.
*
* (c) Alexandre Gomes Gaigalas <alexandre@gaigalas.net>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\ComponentException;
use Sokil\IsoCodes\IsoCodesFactory;
use Sokil\IsoCodes\TranslationDriver\DummyDriver;
use function is_string;
use function sprintf;
/**
* Validates country subdivision codes according to ISO 3166-2.
*
* @see http://en.wikipedia.org/wiki/ISO_3166-2
* @see http://www.geonames.org/countries/
*
* @author Henrique Moody <henriquemoody@gmail.com>
* @author Mazen Touati <mazen_touati@hotmail.com>
*/
final class SubdivisionCode extends AbstractRule
{
/**
* @var string
*/
private $countryCode;
/**
* @var string
*/
private $countryName;
/**
* @var IsoCodesFactory
*/
private $factory;
public function __construct(string $countryCode)
{
$factory = new IsoCodesFactory(null, new DummyDriver());
$country = $factory->getCountries()->getByAlpha2($countryCode);
if ($country === null) {
throw new ComponentException(sprintf('"%s" is not a supported country code', $countryCode));
}
$this->factory = $factory;
$this->countryCode = $countryCode;
$this->countryName = $country->getName();
}
/**
* {@inheritDoc}
*/
public function validate($input): bool
{
if (!is_string($input)) {
return false;
}
return $this->factory->getSubdivisions()->getByCode($this->countryCode . '-' . $input) !== null;
}
}