Skip to content

Rewrite the Luhn Algorithm implementation. #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
index.php
nbproject/
.idea/
.php_cs.cache

# Created by http://www.gitignore.io

Expand Down
14 changes: 14 additions & 0 deletions .php_cs.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'ordered_imports' => true,
'phpdoc_order' => true,
'simplified_null_return' => false,
'no_unused_imports' => true,
])->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__.'/src')
->in(__DIR__.'/tests')
);
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
language: php
php:
- '7.0'
- '7.1'
- '7.2'
before_script: composer install
Expand Down
30 changes: 15 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
[![Build Status](https://travis-ci.org/Ekman/Luhn-Algorithm.svg?branch=master)](https://travis-ci.org/Ekman/Luhn-Algorithm)

This is an implementation of the Luhn Algorithm in PHP. The Luhn Algorithm is
used to validate things like credit cards and national identifcation numbers.
More information on the algorithm can be found at [Wikipedia](http://en.wikipedia.org/wiki/Luhn_algorithm)
used to validate things like credit cards and national identification numbers.
More information on the algorithm can be found at [Wikipedia](http://en.wikipedia.org/wiki/Luhn_algorithm).

## Installation

Can be installed using composer:
Install with [Composer](https://getcomposer.org/):

```bash
composer require nekman/luhn-algorithm
```
Expand All @@ -19,22 +20,21 @@ Use the class like this:

```php
use Nekman\LuhnAlgorithm\LuhnAlgorithmFactory;
use Nekman\LuhnAlgorithm\Number;

$luhn = LuhnAlgorithmFactory::create();

if ($luhn->isValid(123456789)) {
// Number is valid.
// Validate a credit card number entered in a form.
$ccNumber = Number::fromString($creditCard);
if ($luhn->isValid($ccNumber)) {
// Credit card number is valid.
}

$checkSum = $luhn->calcCheckSum(123456789);

$checkDigit = $luhn->calcCheckDigit(123456789);
```
// These methods are used internally by the library. You're free
// to make use of them as well.
$number = new Number(12345);

## Changelog
$checksum = $luhn->calcChecksum($number);

* 4.0.0 - Rewrite of the implementation.
* 3.0.0 - Completely restructured the interface of the library.
* 2.0.1 - Fixed typos in interface.
* 2.0.0 - Added namespace.
* 1.0.0 - Initial release.
$checkDigit = $luhn->calcCheckDigit($number);
```
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@
}
},
"require": {
"php": "^7.0"
"php": "^7.1"
},
"require-dev": {
"phpunit/phpunit": "^6.5"
"phpunit/phpunit": "^6.5",
"friendsofphp/php-cs-fixer": "^2.10"
}
}
129 changes: 63 additions & 66 deletions src/Contract/LuhnAlgorithmInterface.php
Original file line number Diff line number Diff line change
@@ -1,66 +1,63 @@
<?php

/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Niklas Ekman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace Nekman\LuhnAlgorithm\Contract;

/**
* Handles the Luhn Algorithm.
*
* @link http://en.wikipedia.org/wiki/Luhn_algorithm
*/
interface LuhnAlgorithmInterface {
/**
* Determine if a number is valid according to the Luhn Algorithm.
*
* @param string $input The number to validate.
*
* @return bool true if number is valid, false otherwise.
*
* @throws \InvalidArgumentException If the input is invalid.
*/
public function isValid(string $input): bool;

/**
* Calculate the check digit for an input.
*
* @param int $input The input to calculate the check digit for.
*
* @return int The check digit.
*
* @throws \InvalidArgumentException If the input is invalid.
*/
public function calcCheckDigit(int $input): int;

/**
* Calulates the checksum for number.
*
* @param int $input The number to calculate the checksum for.
*
* @return int The checksum.
*
* @throws \InvalidArgumentException If the input is invalid.
*/
public function calcChecksum(int $input): int;
}
<?php

/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Niklas Ekman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace Nekman\LuhnAlgorithm\Contract;

/**
* Handles the Luhn Algorithm.
*
* @link http://en.wikipedia.org/wiki/Luhn_algorithm
*/
interface LuhnAlgorithmInterface
{
/**
* Determine if a number is valid according to the Luhn Algorithm.
*
* @param NumberInterface $number The number to validate.
*
* @return bool true if number is valid, false otherwise.
*/
public function isValid(NumberInterface $number): bool;

/**
* Calculate the check digit for an input.
*
* @param NumberInterface $number The number to calculate the check digit for.
*
* @return int The check digit.
*
*/
public function calcCheckDigit(NumberInterface $number): int;

/**
* Calulates the checksum for number.
*
* @param NumberInterface $number The number to calculate the checksum for.
*
* @return int The checksum.
*
*/
public function calcChecksum(NumberInterface $number): int;
}
46 changes: 46 additions & 0 deletions src/Contract/NumberInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

/*
* The MIT License (MIT)
*
* Copyright (c) 2014 Niklas Ekman
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

namespace Nekman\LuhnAlgorithm\Contract;

/**
* Describes the structure of a number in the Luhn Algorithm.
*/
interface NumberInterface
{
/**
* Get the number, without check digit.
*
* @return int
*/
public function getNumber(): int;

/**
* Get the check digit for the number.
*
* @return int|null The check digit or null if it has not been calculated yet.
*/
public function getCheckDigit(): ?int;
}
105 changes: 54 additions & 51 deletions src/LuhnAlgorithm.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,68 +26,71 @@
namespace Nekman\LuhnAlgorithm;

use Nekman\LuhnAlgorithm\Contract\LuhnAlgorithmInterface;
use Nekman\LuhnAlgorithm\Contract\NumberInterface;

/**
* Handles the Luhn Algorithm.
*
* @link http://en.wikipedia.org/wiki/Luhn_algorithm
* {@inheritdoc}
*/
class LuhnAlgorithm implements LuhnAlgorithmInterface {
/**
* {@inheritDoc}
*/
public function isValid(string $input): bool {
// Remove everything except digits from the input.
$number = (int) preg_replace("/[^\d]/", "", $input);

$checksum = $this->calcChecksum($number);
class LuhnAlgorithm implements LuhnAlgorithmInterface
{
/**
* {@inheritDoc}
*/
public function isValid(NumberInterface $number): bool
{
if ($number->getCheckDigit() === null) {
throw new \InvalidArgumentException("Check digit cannot be null.");
}

// If the checksum is divisible by 10 it is valid
return ($checksum % 10) === 0;
}
$checksum = $this->calcChecksum($number);
$sum = $checksum + $number->getCheckDigit();

/**
* {@inheritDoc}
*/
public function calcCheckDigit(int $input): int {
$checkSum = (string) $this->calcChecksum($input . 0);

// Get the last digit of the checksum
$checkDigit = (int) $checkSum[strlen($checkSum) - 1];
// If the checksum is divisible by 10 it is valid.
return ($sum % 10) === 0;
}

// If the checkdigit is not 0, then subtract the value from 10
return $checkDigit === 0 ? $checkDigit : 10 - $checkDigit;
}
/**
* {@inheritDoc}
*/
public function calcCheckDigit(NumberInterface $number): int
{
$checksum = $this->calcChecksum($number);

// Get the last digit of the checksum.
$checkDigit = $checksum % 10;

/**
* {@inheritDoc}
*/
public function calcChecksum(int $input): int {
$input = (string) $input;
$length = strlen($input);
// If the check digit is not 0, then subtract the value from 10.
return $checkDigit === 0
? $checkDigit
: 10 - $checkDigit;
}

$checkSum = 0;
/**
* {@inheritDoc}
*/
public function calcChecksum(NumberInterface $number): int
{
$number = (string) $number->getNumber();
$nDigits = strlen($number);
$checksum = 0;
$parity = $nDigits % 2;

// Start at the next last digit
for ($i = $length - 2; $i >= 0; $i -= 2) {
// Multiply number with 2
$tmp = (int) ($input[$i]) * 2;
for ($i = 0; $i < $nDigits; $i++) {
$digit = (int) $number[$i];

// If a 2 digit number, split and add togheter
if ($tmp > 9) {
$tmp = ($tmp / 10) + ($tmp % 10);
}
// Every other digit, starting from the leftmost,
// shall be doubled.
if (($i % 2) !== $parity) {
$digit *= 2;

// Sum it upp
$checkSum += $tmp;
}
if ($digit > 9) {
$digit -= 9;
}
}

// Start at the next last digit
for ($i = $length - 1; $i >= 0; $i -= 2) {
// Sum it upp
$checkSum += (int) $input[$i];
}
$checksum += $digit;
}

return $checkSum;
}
return $checksum;
}
}
Loading