|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace IsoCodes; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Class Isbn. |
|
7
|
|
|
* |
|
8
|
|
|
* @author Sullivan Senechal <[email protected]> |
|
9
|
|
|
*/ |
|
10
|
|
|
class Isbn implements IsoCodeInterface |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @param string $isbn |
|
14
|
|
|
* @param int|null $type 10 or 13. Leave empty for both. |
|
15
|
|
|
* |
|
16
|
|
|
* @return bool |
|
17
|
|
|
*/ |
|
18
|
|
|
public static function validate($isbn, $type = null) |
|
19
|
|
|
{ |
|
20
|
|
|
if ($type !== null && !in_array($type, [10, 13], true)) { |
|
21
|
|
|
throw new \InvalidArgumentException('ISBN type option must be 10 or 13'); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
$isbn = str_replace(' ', '', $isbn); |
|
25
|
|
|
$isbn = str_replace('-', '', $isbn); // this is a dash |
|
26
|
|
|
$isbn = str_replace('‐', '', $isbn); // this is an authentic hyphen |
|
27
|
|
|
|
|
28
|
|
|
if ($type === 10) { |
|
29
|
|
|
return self::validateIsbn10($isbn); |
|
30
|
|
|
} |
|
31
|
|
|
if ($type === 13) { |
|
32
|
|
|
return self::validateIsbn13($isbn); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
return self::validateIsbn10($isbn) || self::validateIsbn13($isbn); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
private static function validateIsbn10($isbn10) |
|
39
|
|
|
{ |
|
40
|
|
|
if (strlen($isbn10) != 10) { |
|
41
|
|
|
return false; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if (!preg_match('/\\d{9}[0-9xX]/i', $isbn10)) { |
|
45
|
|
|
return false; |
|
46
|
|
|
} |
|
47
|
|
|
$check = 0; |
|
48
|
|
|
for ($i = 0; $i < 10; ++$i) { |
|
49
|
|
|
if ($isbn10[$i] == 'X') { |
|
50
|
|
|
$check += 10 * intval(10 - $i); |
|
51
|
|
|
} |
|
52
|
|
|
$check += intval($isbn10[$i]) * intval(10 - $i); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
return $check % 11 == 0; |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
private static function validateIsbn13($isbn13) |
|
59
|
|
|
{ |
|
60
|
|
|
if (strlen($isbn13) != 13 || !ctype_digit($isbn13)) { |
|
61
|
|
|
return false; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return Luhn::check($isbn13, 13, false); |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|