<?php
class IdentificationNumber
{
private const VALIDATION_EXPR = '/
^
(?<part1> \d{1,2} | N | P?E | \d{1,2}PI )
-
(?<part2> \d{1,5} )
-
(?<part3> \d{1,6} )
$
/ix';
private $part1;
private $part2;
private $part3;
public function __construct(string $input)
{
if (!\preg_match(self::VALIDATION_EXPR, $input, $match)) {
throw new \DomainException('Invalid identification number: ' . $input);
}
$this->part1 = \strtoupper($match['part1']);
$this->part2 = $match['part2'];
$this->part3 = $match['part3'];
}
public function getPart1(): string
{
return $this->part1;
}
public function getPart2(): string
{
return $this->part2;
}
public function getPart3(): string
{
return $this->part3;
}
public function __toString(): string
{
return "{$this->part1}-{$this->part2}-{$this->part3}";
}
}
function procedure_that_needs_valid_id(IdentificationNumber $id)
{
echo "{$id} is valid\n";
}
$tests = [
'3-728-2208',
'1-728-2208',
'22PI-55555-666666',
'PE-333-333',
'PÉ-1-4444',
'N-4444-55555',
'Ñ-22-22',
'E-1-1',
];
foreach ($tests as $test) {
try {
procedure_that_needs_valid_id(new IdentificationNumber($test));
} catch (\DomainException $e) {
echo "{$e->getMessage()}\n";
}
}
preferences:
25.8 ms | 402 KiB | 5 Q