Ean.php
5 years ago
Iban.php
5 years ago
Inn.php
5 years ago
Luhn.php
5 years ago
TCNo.php
5 years ago
Ean.php
56 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Faker\Calculator; |
| 4 | |
| 5 | /** |
| 6 | * Utility class for validating EAN-8 and EAN-13 numbers |
| 7 | * |
| 8 | * @package Faker\Calculator |
| 9 | */ |
| 10 | class Ean |
| 11 | { |
| 12 | /** @var string EAN validation pattern */ |
| 13 | const PATTERN = '/^(?:\d{8}|\d{13})$/'; |
| 14 | |
| 15 | /** |
| 16 | * Computes the checksum of an EAN number. |
| 17 | * |
| 18 | * @see https://en.wikipedia.org/wiki/International_Article_Number |
| 19 | * |
| 20 | * @param string $digits |
| 21 | * @return int |
| 22 | */ |
| 23 | public static function checksum($digits) |
| 24 | { |
| 25 | $length = strlen($digits); |
| 26 | |
| 27 | $even = 0; |
| 28 | for ($i = $length - 1; $i >= 0; $i -= 2) { |
| 29 | $even += $digits[$i]; |
| 30 | } |
| 31 | |
| 32 | $odd = 0; |
| 33 | for ($i = $length - 2; $i >= 0; $i -= 2) { |
| 34 | $odd += $digits[$i]; |
| 35 | } |
| 36 | |
| 37 | return (10 - ((3 * $even + $odd) % 10)) % 10; |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Checks whether the provided number is an EAN compliant number and that |
| 42 | * the checksum is correct. |
| 43 | * |
| 44 | * @param string $ean An EAN number |
| 45 | * @return boolean |
| 46 | */ |
| 47 | public static function isValid($ean) |
| 48 | { |
| 49 | if (!preg_match(self::PATTERN, $ean)) { |
| 50 | return false; |
| 51 | } |
| 52 | |
| 53 | return self::checksum(substr($ean, 0, -1)) === intval(substr($ean, -1)); |
| 54 | } |
| 55 | } |
| 56 |