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 ISBN-10
7
 */
8
class Isbn
9
{
10
    /**
11
     * @var string ISBN-10 validation pattern
12
     */
13
    public const PATTERN = '/^\d{9}[0-9X]$/';
14
 
15
    /**
16
     * ISBN-10 check digit
17
     *
18
     * @see http://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digits
19
     *
20
     * @param string $input ISBN without check-digit
21
     *
22
     * @throws \LengthException When wrong input length passed
23
     */
24
    public static function checksum(string $input): string
25
    {
26
        // We're calculating check digit for ISBN-10
27
        // so, the length of the input should be 9
28
        $length = 9;
29
 
30
        if (strlen($input) !== $length) {
31
            throw new \LengthException(sprintf('Input length should be equal to %d', $length));
32
        }
33
 
34
        $digits = str_split($input);
35
        array_walk(
36
            $digits,
37
            static function (&$digit, $position): void {
38
                $digit = (10 - $position) * $digit;
39
            },
40
        );
41
        $result = (11 - array_sum($digits) % 11) % 11;
42
 
43
        // 10 is replaced by X
44
        return ($result < 10) ? (string) $result : 'X';
45
    }
46
 
47
    /**
48
     * Checks whether the provided number is a valid ISBN-10 number
49
     *
50
     * @param string $isbn ISBN to check
51
     */
52
    public static function isValid(string $isbn): bool
53
    {
54
        if (!preg_match(self::PATTERN, $isbn)) {
55
            return false;
56
        }
57
 
58
        return self::checksum(substr($isbn, 0, -1)) === substr($isbn, -1);
59
    }
60
}