From a4f074b4ebf70592d713871fc8e2118d5c0a52f6 Mon Sep 17 00:00:00 2001 From: Pol Dellaiera Date: Thu, 6 Jun 2024 20:31:01 +0200 Subject: [PATCH] feat: add `strict` parameter to `check` and `isValid` Context: https://github.com/loophp/tin/pull/39#issuecomment-2153095704 --- src/TIN.php | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/TIN.php b/src/TIN.php index 21ae38b..de616a6 100644 --- a/src/TIN.php +++ b/src/TIN.php @@ -92,9 +92,9 @@ private function __construct(string $slug) /** * @throws TINException */ - public function check(): bool + public function check(bool $strict = false): bool { - $parsedTin = $this->parse($this->slug); + $parsedTin = $this->parse($this->slug, $strict); return $this->getAlgorithm($parsedTin['country'], $parsedTin['tin'])->validate(); } @@ -109,10 +109,10 @@ public static function fromSlug(string $slug): TIN return new self($slug); } - public function isValid(): bool + public function isValid(bool $strict = false): bool { try { - $this->check(); + $this->check($strict); } catch (TINException $e) { return false; } @@ -138,12 +138,21 @@ private function getAlgorithm(string $country, ?string $tin = null): CountryHand throw TINException::invalidCountry($country); } + private function normalizeTin(string $tin): string + { + if (null !== $string = preg_replace('#[^[:alnum:]\-+]#u', '', $tin)) { + return strtoupper($string); + } + + return ''; + } + /** * @throws TINException * * @return non-empty-array<'country'|'tin', string> */ - private function parse(string $slug): array + private function parse(string $slug, bool $strict): array { if ('' === $slug) { throw TINException::emptySlug(); @@ -153,7 +162,7 @@ private function parse(string $slug): array return [ 'country' => (string) $country, - 'tin' => (string) $tin, + 'tin' => true === $strict ? $this->normalizeTin((string) $tin) : (string) $tin, ]; } }