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 validating EAN-8 and EAN-13 numbers
7
 */
8
class Ean
9
{
10
    /**
11
     * @var string EAN validation pattern
12
     */
13
    public 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
     *
22
     * @return int
23
     */
24
    public static function checksum($digits)
25
    {
26
        $sequence = (strlen($digits) + 1) === 8 ? [3, 1] : [1, 3];
27
        $sums = 0;
28
 
29
        foreach (str_split($digits) as $n => $digit) {
30
            $sums += ((int) $digit) * $sequence[$n % 2];
31
        }
32
 
33
        return (10 - $sums % 10) % 10;
34
    }
35
 
36
    /**
37
     * Checks whether the provided number is an EAN compliant number and that
38
     * the checksum is correct.
39
     *
40
     * @param string $ean An EAN number
41
     *
42
     * @return bool
43
     */
44
    public static function isValid($ean)
45
    {
46
        if (!preg_match(self::PATTERN, $ean)) {
47
            return false;
48
        }
49
 
50
        return self::checksum(substr($ean, 0, -1)) === (int) substr($ean, -1);
51
    }
52
}