Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
namespace Faker\Calculator;
4
 
5
/**
6
 * Utility class for generating and validating Luhn numbers.
7
 *
8
 * Luhn algorithm is used to validate credit card numbers, IMEI numbers, and
9
 * National Provider Identifier numbers.
10
 *
11
 * @see http://en.wikipedia.org/wiki/Luhn_algorithm
12
 */
13
class Luhn
14
{
15
    /**
16
     * @param string $number
17
     *
18
     * @return int
19
     */
20
    private static function checksum($number)
21
    {
22
        $number = (string) $number;
23
        $length = strlen($number);
24
        $sum = 0;
25
 
26
        for ($i = $length - 1; $i >= 0; $i -= 2) {
27
            $sum += $number[$i];
28
        }
29
 
30
        for ($i = $length - 2; $i >= 0; $i -= 2) {
31
            $sum += array_sum(str_split($number[$i] * 2));
32
        }
33
 
34
        return $sum % 10;
35
    }
36
 
37
    /**
38
     * @param string $partialNumber
39
     *
40
     * @return string
41
     */
42
    public static function computeCheckDigit($partialNumber)
43
    {
44
        $checkDigit = self::checksum($partialNumber . '0');
45
 
46
        if ($checkDigit === 0) {
47
            return 0;
48
        }
49
 
50
        return (string) (10 - $checkDigit);
51
    }
52
 
53
    /**
54
     * Checks whether a number (partial number + check digit) is Luhn compliant
55
     *
56
     * @param string $number
57
     *
58
     * @return bool
59
     */
60
    public static function isValid($number)
61
    {
62
        return self::checksum($number) === 0;
63
    }
64
 
65
    /**
66
     * Generate a Luhn compliant number.
67
     *
68
     * @param string $partialValue
69
     *
70
     * @return string
71
     */
72
    public static function generateLuhnNumber($partialValue)
73
    {
74
        if (!preg_match('/^\d+$/', $partialValue)) {
75
            throw new \InvalidArgumentException('Argument should be an integer.');
76
        }
77
 
78
        return $partialValue . Luhn::computeCheckDigit($partialValue);
79
    }
80
}