added countries support expanded for ISO 3166 standard

This commit is contained in:
Mark Gregory
2026-06-15 09:27:57 +01:00
parent 76521e07fe
commit 3638e34535
21 changed files with 771 additions and 50 deletions
+1 -15
View File
@@ -4,7 +4,6 @@ namespace Modules\Countries\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Modules\Countries\Models\Country;
class ValidCountryCode implements ValidationRule
{
@@ -14,19 +13,6 @@ class ValidCountryCode implements ValidationRule
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! is_string($value) || strlen($value) !== 2) {
$fail('The :attribute must be a valid ISO 3166 alpha-2 country code.');
return;
}
$query = Country::query()->where('alpha2', strtoupper($value));
if ($this->activeOnly) {
$query->where('is_active', true);
}
if (! $query->exists()) {
$fail('The :attribute must be a supported country.');
}
(new ValidIso3166CountryCode($this->activeOnly, 'alpha2'))->validate($attribute, $value, $fail);
}
}
@@ -0,0 +1,43 @@
<?php
namespace Modules\Countries\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Modules\Countries\Models\Country;
class ValidIso3166CountryCode implements ValidationRule
{
public function __construct(
private readonly bool $activeOnly = true,
private readonly string $format = 'alpha2',
) {
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! is_string($value) && ! is_int($value)) {
$fail('The :attribute must be a valid ISO 3166 country code.');
return;
}
$code = strtoupper(trim((string) $value));
$query = Country::query();
match ($this->format) {
'alpha2' => $query->where('alpha2', $code),
'alpha3' => $query->where('alpha3', $code),
'numeric' => $query->where('numeric', str_pad($code, 3, '0', STR_PAD_LEFT)),
'any' => $query->forIsoCode($code),
default => $query->whereRaw('1 = 0'),
};
if ($this->activeOnly) {
$query->where('is_active', true);
}
if (! $query->exists()) {
$fail('The :attribute must be a supported ISO 3166 country code.');
}
}
}
@@ -0,0 +1,32 @@
<?php
namespace Modules\Countries\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Modules\Countries\Models\CountrySubdivision;
class ValidIso3166SubdivisionCode implements ValidationRule
{
public function __construct(private readonly bool $activeOnly = true)
{
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (! is_string($value) || ! preg_match('/^[A-Z]{2}-[A-Z0-9]{1,6}$/', strtoupper($value))) {
$fail('The :attribute must be a valid ISO 3166-2 subdivision code.');
return;
}
$query = CountrySubdivision::query()->where('code', strtoupper($value));
if ($this->activeOnly) {
$query->where('is_active', true);
}
if (! $query->exists()) {
$fail('The :attribute must be a supported ISO 3166-2 subdivision code.');
}
}
}