Skip to content

Commit

Permalink
Merge pull request #6 from marvinlabs/develop
Browse files Browse the repository at this point in the history
 Add extra tests for 0 and fix empty string error.
  • Loading branch information
vpratfr authored Nov 7, 2018
2 parents 5ce2655 + 4685acc commit 1c2b36c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/Luhn/Algorithm/LuhnAlgorithm.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace MarvinLabs\Luhn\Algorithm;

use InvalidArgumentException;
use MarvinLabs\Luhn\Contracts\LuhnAlgorithm as LuhnAlgorithmContract;

/**
Expand All @@ -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;
Expand Down Expand Up @@ -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],
Expand Down
2 changes: 2 additions & 0 deletions tests/AlgorithmTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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],
];
Expand Down

0 comments on commit 1c2b36c

Please sign in to comment.