respect-validation/library/Rules/SubdivisionCode.php
Henrique Moody 04b2722d02
Remove ISO 3166-2 data in favor of PHP ISO codes
Keeping the list of ISO 3166-2 up-to-date requires some maintenance. At
the same time, PHP ISO Codes maintains an up-to-date database with even
more ISO codes we could use in this library.

This change doesn't fully use all resources of PHP ISO Codes, but it
already removes some unnecessary code from the repository.

We've already used this library, but it was heavy because it included
all the localizations in it. Now, the package is much smaller (5.0M).

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2024-02-13 21:53:46 +01:00

74 lines
2.2 KiB
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Respect\Validation\Exceptions\InvalidRuleConstructorException;
use Respect\Validation\Exceptions\MissingComposerDependencyException;
use Respect\Validation\Message\Template;
use Sokil\IsoCodes\Database\Countries;
use Sokil\IsoCodes\Database\Subdivisions;
use function array_map;
use function class_exists;
use function str_replace;
#[Template(
'{{name}} must be a subdivision code of {{countryName}}',
'{{name}} must not be a subdivision code of {{countryName}}',
)]
final class SubdivisionCode extends AbstractSearcher
{
private readonly Countries\Country $country;
private readonly Subdivisions $subdivisions;
public function __construct(string $countryCode, ?Countries $countries = null, ?Subdivisions $subdivisions = null)
{
if (!class_exists(Countries::class) || !class_exists(Subdivisions::class)) {
throw new MissingComposerDependencyException(
'SubdivisionCode rule requires PHP ISO Codes',
'sokil/php-isocodes',
'sokil/php-isocodes-db-only'
);
}
$countries ??= new Countries();
$country = $countries->getByAlpha2($countryCode);
if ($country === null) {
throw new InvalidRuleConstructorException('"%s" is not a supported country code', $countryCode);
}
$this->country = $country;
$this->subdivisions = $subdivisions ?? new Subdivisions();
}
/**
* @return array<string, mixed>
*/
public function getParams(): array
{
return ['countryName' => $this->country->getName()];
}
/**
* @return array<int, string>
*/
protected function getDataSource(mixed $input = null): array
{
return array_map(
fn (Subdivisions\Subdivision $subdivision): string => str_replace(
$this->country->getAlpha2() . '-',
'',
$subdivision->getCode(),
),
$this->subdivisions->getAllByCountryCode($this->country->getAlpha2()),
);
}
}