From 7481452c1094bfd91968f824e289e5fde8e3706a Mon Sep 17 00:00:00 2001 From: Lucas Michot Date: Sat, 22 Sep 2018 17:57:49 +0200 Subject: [PATCH] Add extra tests for 0 and fix empty string error. --- src/Luhn/Algorithm/LuhnAlgorithm.php | 12 +++++++++++- tests/AlgorithmTest.php | 2 ++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/Luhn/Algorithm/LuhnAlgorithm.php b/src/Luhn/Algorithm/LuhnAlgorithm.php index 5600b54..37fbad4 100644 --- a/src/Luhn/Algorithm/LuhnAlgorithm.php +++ b/src/Luhn/Algorithm/LuhnAlgorithm.php @@ -2,6 +2,7 @@ namespace MarvinLabs\Luhn\Algorithm; +use InvalidArgumentException; use MarvinLabs\Luhn\Contracts\LuhnAlgorithm as LuhnAlgorithmContract; /** @@ -12,7 +13,11 @@ class LuhnAlgorithm implements LuhnAlgorithmContract public function isValid(string $input): bool { - [$number, $lastDigit] = $this->cleanAndSplitInput($input); + try { + [$number, $lastDigit] = $this->cleanAndSplitInput($input); + } catch (InvalidArgumentException $e) { + return false; + } $checksum = $this->computeCheckSum($number); $sum = $checksum + $lastDigit; @@ -59,6 +64,11 @@ protected function cleanAndSplitInput(string $input): array // Remove everything not a digit, then extract check digit $input = \preg_replace('/\D/', '', $input); $inputLength = \strlen($input); + + if ($inputLength === 0) { + throw new InvalidArgumentException; + } + return [ \substr($input, 0, $inputLength - 1), (int)$input[$inputLength - 1], diff --git a/tests/AlgorithmTest.php b/tests/AlgorithmTest.php index 95e6e0d..3f1a8ff 100644 --- a/tests/AlgorithmTest.php +++ b/tests/AlgorithmTest.php @@ -21,11 +21,13 @@ public function provideIsValidTestInput(): array { return [ 'default' => ['837668185', true], + 'zero' => ['0', true], 'with_spaces' => ['837 668 185', true], '123455' => ['123455', true], '4103219202' => ['4103219202', true], '31997233700020' => ['31997233700020', true], 'large' => ['89148000003974165685', true], + 'empty' => ['', false], 'invalid' => ['123456789', false], '123' => ['123', false], ];