Skip to content

Commit

Permalink
feat: add strict parameter to check and isValid
Browse files Browse the repository at this point in the history
Context: #39 (comment)
  • Loading branch information
drupol committed Jun 6, 2024
1 parent c916eda commit a4f074b
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions src/TIN.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand All @@ -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;
}
Expand All @@ -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();
Expand All @@ -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,
];
}
}

0 comments on commit a4f074b

Please sign in to comment.