├── .github └── FUNDING.yml ├── .editorconfig ├── tests ├── FunctionsTest.php ├── LuhnAlgorithmFactoryTest.php ├── LuhnAlgorithmTest.php └── NumberTest.php ├── LICENSE.md ├── .gitignore ├── composer.json ├── src ├── Contract │ ├── LuhnAlgorithmExceptionInterface.php │ ├── NumberInterface.php │ └── LuhnAlgorithmInterface.php ├── Exceptions │ ├── MissingCheckDigitException.php │ └── ArgumentIsNotNumericException.php ├── functions.php ├── LuhnAlgorithmFactory.php ├── LuhnAlgorithm.php └── Number.php ├── .circleci └── config.yml └── README.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | buy_me_a_coffee: nekman 2 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # See: https://editorconfig.org/#file-format-details 2 | root = true 3 | 4 | [*] 5 | end_of_line = lf 6 | insert_final_newline = true 7 | charset = utf-8 8 | indent_style = tab 9 | trim_trailing_whitespace = true 10 | indent_size = 4 11 | 12 | [*.yml] 13 | indent_style = space 14 | indent_size = 2 15 | -------------------------------------------------------------------------------- /tests/FunctionsTest.php: -------------------------------------------------------------------------------- 1 | assertEquals($expected, string_is_numeric($string)); 14 | } 15 | 16 | public function provideStringIsNumeric() 17 | { 18 | return [ 19 | "integer string" => ["123", true], 20 | "float string" => ["123.321", true], 21 | "whitespace" => ["123 ", false], 22 | "integer" => [123, true], 23 | "float" => [123.321, true], 24 | ]; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2021 Niklas Ekman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | this software and associated documentation files (the "Software"), to deal in 7 | the Software without restriction, including without limitation the rights to 8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software is furnished to do so, 10 | subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | index.php 2 | nbproject/ 3 | .idea/ 4 | .php_cs.cache 5 | .phpunit.result.cache 6 | coverage 7 | test-results 8 | 9 | # Eclipse 10 | .buildpath 11 | .project 12 | .settings/ 13 | 14 | # Created by http://www.gitignore.io 15 | 16 | ### Composer ### 17 | composer.phar 18 | vendor/ 19 | 20 | # Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file 21 | # You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file 22 | composer.lock 23 | 24 | ### Windows ### 25 | # Windows image file caches 26 | Thumbs.db 27 | ehthumbs.db 28 | 29 | # Folder config file 30 | Desktop.ini 31 | 32 | # Recycle Bin used on file shares 33 | $RECYCLE.BIN/ 34 | 35 | # Windows Installer files 36 | *.cab 37 | *.msi 38 | *.msm 39 | *.msp 40 | 41 | 42 | ### OSX ### 43 | .DS_Store 44 | .AppleDouble 45 | .LSOverride 46 | 47 | # Icon must ends with two \r. 48 | Icon 49 | 50 | 51 | # Thumbnails 52 | ._* 53 | 54 | # Files that might appear on external disk 55 | .Spotlight-V100 56 | .Trashes 57 | 58 | 59 | ### Linux ### 60 | *~ 61 | 62 | 63 | ### NetBeans ### 64 | nbproject/private/ 65 | build/ 66 | nbbuild/ 67 | dist/ 68 | nbdist/ 69 | nbactions.xml 70 | nb-configuration.xml 71 | nbproject/ 72 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nekman/luhn-algorithm", 3 | "type": "library", 4 | "description": "Implementation of the Luhn algorithm in PHP. Used in validation of credit card numbers and some national identification numbers.", 5 | "prefer-stable": true, 6 | "minimum-stability": "stable", 7 | "keywords": [ 8 | "luhn", 9 | "credit", 10 | "card", 11 | "identification", 12 | "validation" 13 | ], 14 | "license": "MIT", 15 | "authors": [ 16 | { 17 | "name": "Niklas Ekman", 18 | "email": "nikl.ekman@gmail.com" 19 | } 20 | ], 21 | "support": { 22 | "issues": "https://github.com/Ekman/Luhn-Algorithm/issues", 23 | "source": "https://github.com/Ekman/Luhn-Algorithm" 24 | }, 25 | "autoload": { 26 | "psr-4": { 27 | "Nekman\\LuhnAlgorithm\\": "src" 28 | }, 29 | "files": [ 30 | "src/functions.php" 31 | ] 32 | }, 33 | "autoload-dev": { 34 | "psr-4": { 35 | "Nekman\\LuhnAlgorithm\\Test\\": "tests" 36 | } 37 | }, 38 | "require": { 39 | "php": "^7.4||^8.0" 40 | }, 41 | "require-dev": { 42 | "phpunit/phpunit": "^9.0", 43 | "friendsofphp/php-cs-fixer": "^2.15", 44 | "php-coveralls/php-coveralls": "^2.1" 45 | }, 46 | "scripts": { 47 | "test": "phpunit tests", 48 | "lint": "php-cs-fixer fix --rules=@PSR2 ." 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Contract/LuhnAlgorithmExceptionInterface.php: -------------------------------------------------------------------------------- 1 | assertInstanceOf(LuhnAlgorithm::class, LuhnAlgorithmFactory::create()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Exceptions/MissingCheckDigitException.php: -------------------------------------------------------------------------------- 1 | isValid($number)) { 37 | // Number is valid. 38 | } 39 | ``` 40 | 41 | Alternatively, if you want to calculate the checksum or check digit for a number: 42 | 43 | ```php 44 | use Nekman\LuhnAlgorithm\Number; 45 | 46 | $number = new Number(12345); 47 | 48 | $checksum = $luhn->calcChecksum($number); 49 | 50 | $checkDigit = $luhn->calcCheckDigit($number); 51 | ``` 52 | 53 | ## Versioning 54 | 55 | This project complies with [Semantic Versioning](https://semver.org/). 56 | 57 | ## Changelog 58 | 59 | For a complete list of changes, and how to migrate between major versions, see [releases page](https://github.com/Ekman/luhn-algorithm/releases). 60 | 61 | ## Buy me a coffee 62 | 63 | [!["Buy Me A Coffee"](https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png)](https://buymeacoffee.com/nekman) 64 | 65 | If you appreciate my work, then consider [buying me a coffee](https://buymeacoffee.com/nekman). Donations are completely voluntary. 66 | -------------------------------------------------------------------------------- /src/Contract/LuhnAlgorithmInterface.php: -------------------------------------------------------------------------------- 1 | getCheckDigit() === null) { 51 | throw new MissingCheckDigitException("Check digit is null."); 52 | } 53 | 54 | $checksum = $this->calcChecksum($number) + $number->getCheckDigit(); 55 | 56 | return ($checksum % 10) === 0; 57 | } 58 | 59 | /** 60 | * {@inheritDoc} 61 | */ 62 | public function calcChecksum(NumberInterface $number): int 63 | { 64 | $num = $number->getNumber(); 65 | $nDigits = strlen($num); 66 | // Need to account for check digit 67 | $parity = ($nDigits + 1) % 2; 68 | $checksum = 0; 69 | 70 | for ($i = 0; $i < $nDigits; $i++) { 71 | $digit = (int)$num[$i]; 72 | 73 | // Every other digit, starting from the rightmost, 74 | // shall be doubled. 75 | if (($i % 2) === $parity) { 76 | $digit *= 2; 77 | 78 | if ($digit > 9) { 79 | $digit -= 9; 80 | } 81 | } 82 | 83 | $checksum += $digit; 84 | } 85 | 86 | return $checksum; 87 | } 88 | 89 | /** 90 | * {@inheritDoc} 91 | */ 92 | public function calcCheckDigit(NumberInterface $number): int 93 | { 94 | $checksum = $this->calcChecksum($number); 95 | 96 | // Get the last digit of the checksum. 97 | $checkDigit = $checksum % 10; 98 | 99 | return $checkDigit === 0 100 | ? $checkDigit 101 | : 10 - $checkDigit; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/Number.php: -------------------------------------------------------------------------------- 1 | number = $number; 56 | $this->checkDigit = $checkDigit; 57 | } 58 | 59 | /** 60 | * Create a new number from an input that contains the check digit already 61 | * @param string $input The input that contains the check digit already. 62 | * @return self 63 | * 64 | * @throws LuhnAlgorithmExceptionInterface 65 | * @throws ArgumentIsNotNumericException If the input does not consist entirely of numbers. 66 | */ 67 | public static function fromString(string $input): self 68 | { 69 | $input = preg_replace('/[^\d]/', '', $input); 70 | 71 | if (!string_is_numeric($input)) { 72 | throw new ArgumentIsNotNumericException($input); 73 | } 74 | 75 | $lastIndex = strlen($input) - 1; 76 | 77 | // Get the last digit. 78 | $checkDigit = (int)$input[$lastIndex]; 79 | 80 | // Remove the last digit. 81 | $number = substr($input, 0, $lastIndex); 82 | 83 | return new self($number, $checkDigit); 84 | } 85 | 86 | public function __toString(): string 87 | { 88 | return $this->number . $this->checkDigit; 89 | } 90 | 91 | /** 92 | * {@inheritdoc} 93 | */ 94 | public function getCheckDigit(): ?int 95 | { 96 | return $this->checkDigit; 97 | } 98 | 99 | /** 100 | * {@inheritdoc} 101 | */ 102 | public function getNumber(): string 103 | { 104 | return $this->number; 105 | } 106 | 107 | public function serialize(): string 108 | { 109 | return serialize($this->__serialize()); 110 | } 111 | 112 | public function __serialize(): array 113 | { 114 | return [$this->number, $this->checkDigit]; 115 | } 116 | 117 | public function unserialize($data): void 118 | { 119 | $this->__unserialize(unserialize($data)); 120 | } 121 | 122 | public function __unserialize(array $data): void 123 | { 124 | [$this->number, $this->checkDigit] = $data; 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /tests/LuhnAlgorithmTest.php: -------------------------------------------------------------------------------- 1 | assertEquals($expected, $this->luhn->isValid($number)); 48 | } 49 | 50 | public function provideIsValid_success() 51 | { 52 | return [ 53 | "Valid number" => [new Number('12345', 5), true], 54 | "Zero" => [new Number('0', 0), true], 55 | "Larger than INT_MAX" => [new Number('92233720368547758072', 8), true], 56 | "Invalid number" => [new Number('12345', 6), false], 57 | "Swedish company organization ID" => [new Number(559114884, 5), true], 58 | "Swedish organization number" => [new Number(640319261, 7), true], 59 | ]; 60 | } 61 | 62 | /** 63 | * @dataProvider provideIsValid_failure 64 | */ 65 | public function testIsValid_failure($number, $exception) 66 | { 67 | $this->expectException($exception); 68 | $this->luhn->isValid($number); 69 | } 70 | 71 | public function provideIsValid_failure() 72 | { 73 | return [ 74 | "Invalid argument" => [new Number(123, null), InvalidArgumentException::class], 75 | "Should be MissingCheckDigitException" => [new Number(123, null), MissingCheckDigitException::class], 76 | "Should be LuhnAlgorithmExceptionInterface" => [new Number(123, null), LuhnAlgorithmExceptionInterface::class], 77 | ]; 78 | } 79 | 80 | /** 81 | * @dataProvider provideCalcChecksum_success 82 | */ 83 | public function testCalcChecksum_success($number, $expected) 84 | { 85 | $this->assertEquals($expected, $this->luhn->calcChecksum($number)); 86 | } 87 | 88 | public function provideCalcChecksum_success() 89 | { 90 | return [ 91 | "Valid checksum" => [new Number(3199723370002), 50], 92 | "Checksum mod 10 is 0" => [new Number(31997), 30], 93 | ]; 94 | } 95 | 96 | /** 97 | * @dataProvider provideCalcCheckDigit_success 98 | */ 99 | public function testCalcCheckDigit_success($number, $expected) 100 | { 101 | $this->assertEquals($expected, $this->luhn->calcCheckDigit($number)); 102 | } 103 | 104 | public function provideCalcCheckDigit_success() 105 | { 106 | return [ 107 | "Valid number" => [new Number(12345), 5], 108 | "Swedish company organization ID" => [new Number(559114884), 5], 109 | "Swedish organization number" => [new Number(640319261), 7], 110 | "Checksum mod 10 is 0" => [new Number(31997), 0], 111 | ]; 112 | } 113 | 114 | protected function setUp(): void 115 | { 116 | parent::setUp(); 117 | 118 | $this->luhn = new LuhnAlgorithm(); 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /tests/NumberTest.php: -------------------------------------------------------------------------------- 1 | assertEquals($expected, Number::fromString($number)); 41 | } 42 | 43 | public function provideFromString_success() 44 | { 45 | return [ 46 | "String" => ["410321-9202", new Number('410321920', 2)], 47 | "Integer" => [4103219202, new Number('410321920', 2)], 48 | "Large number" => ['89148000003974165685', new Number('8914800000397416568', 5)], 49 | "Character in string" => ['abc123', new Number('12', 3)], 50 | "Larger than INT_MAX" => ['922337203685477580721', new Number('92233720368547758072', 1)], 51 | ]; 52 | } 53 | 54 | /** 55 | * @dataProvider provideFromString_fail 56 | */ 57 | public function testFromString_fail($number, $expected) 58 | { 59 | $this->expectException($expected); 60 | Number::fromString($number); 61 | } 62 | 63 | public function provideFromString_fail() 64 | { 65 | return [ 66 | "Empty string" => ['', \InvalidArgumentException::class], 67 | "Invalid string" => ['xyz ', \InvalidArgumentException::class], 68 | "Should be ArgumentIsNotNullException" => ["foo", ArgumentIsNotNumericException::class], 69 | "Should be LuhnAlgorithmExceptionInterface" => ["bar", LuhnAlgorithmExceptionInterface::class], 70 | ]; 71 | } 72 | 73 | /** 74 | * @dataProvider provideToString_success 75 | */ 76 | public function testToString_success($number, $expected) 77 | { 78 | $this->assertEquals($expected, (string)$number); 79 | } 80 | 81 | public function provideToString_success() 82 | { 83 | return [ 84 | "Valid number" => [new Number(12345, 5), "123455"] 85 | ]; 86 | } 87 | 88 | /** 89 | * @dataProvider provideNew_fail 90 | */ 91 | public function testNew_fail($number, $checkDigit, $expected) 92 | { 93 | $this->expectException($expected); 94 | new Number($number, $checkDigit); 95 | } 96 | 97 | public function provideNew_fail() 98 | { 99 | return [ 100 | "Invalid number" => ['abc123', 1, \InvalidArgumentException::class], 101 | "Whitespace" => ['123 ', null, \InvalidArgumentException::class], 102 | "Should be ArgumentIsNotNullException" => ["foo", null, ArgumentIsNotNumericException::class], 103 | "Should be LuhnAlgorithmExceptionInterface" => ["bar", null, LuhnAlgorithmExceptionInterface::class], 104 | ]; 105 | } 106 | 107 | /** 108 | * @dataProvider provideProperties 109 | */ 110 | public function testProperties($input, $checkDigit) 111 | { 112 | $number = new Number($input, $checkDigit); 113 | $this->assertEquals($input, $number->getNumber()); 114 | $this->assertEquals($checkDigit, $number->getCheckDigit()); 115 | } 116 | 117 | public function provideProperties() 118 | { 119 | return [ 120 | "Valid number and check digit" => [123, 1], 121 | "Valid number and check digit (null)" => [123, null], 122 | ]; 123 | } 124 | 125 | public function testSerialize() 126 | { 127 | $number = new Number(133, 7); 128 | $serialized = serialize($number); 129 | $other = unserialize($serialized); 130 | $this->assertInstanceOf(Number::class, $other); 131 | $this->assertEquals(133, $other->getNumber()); 132 | $this->assertEquals(7, $other->getCheckDigit()); 133 | } 134 | } 135 | --------------------------------------------------------------------------------