respect-validation/library/Rules/PolishIdCard.php
Henrique Moody 48405271c5
Replace placeholder "name" with "subject"
The `{{name}}` placeholder could represent different things depending on
the state of the Result, and referring to it as `{{name}}` seems
arbitrary. This commit changes it to `{{subject}}`, which is much more
generic and it describes well what that placeholder can mean.
2025-12-26 21:30:01 +01:00

63 lines
1.6 KiB
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Attribute;
use Respect\Validation\Message\Template;
use Respect\Validation\Rules\Core\Simple;
use function is_scalar;
use function ord;
use function preg_match;
/** @see https://en.wikipedia.org/wiki/Polish_identity_card */
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
#[Template(
'{{subject}} must be a valid Polish Identity Card number',
'{{subject}} must not be a valid Polish Identity Card number',
)]
final class PolishIdCard extends Simple
{
private const int ASCII_CODE_0 = 48;
private const int ASCII_CODE_7 = 55;
private const int ASCII_CODE_9 = 57;
private const int ASCII_CODE_A = 65;
public function isValid(mixed $input): bool
{
if (!is_scalar($input)) {
return false;
}
$input = (string) $input;
if (!preg_match('/^[A-Z0-9]{9}$/', $input)) {
return false;
}
$weights = [7, 3, 1, 0, 7, 3, 1, 7, 3];
$weightedSum = 0;
for ($i = 0; $i < 9; ++$i) {
$code = ord($input[$i]);
if ($i < 3 && $code <= self::ASCII_CODE_9) {
return false;
}
if ($i > 2 && $code >= self::ASCII_CODE_A) {
return false;
}
$difference = $code <= self::ASCII_CODE_9 ? self::ASCII_CODE_0 : self::ASCII_CODE_7;
$weightedSum += ($code - $difference) * $weights[$i];
}
return $weightedSum % 10 == $input[3];
}
}