|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of Dimtrovich/Validation. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) 2023 Dimitri Sitchet Tomkeu <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view |
|
9
|
|
|
* the LICENSE file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Dimtrovich\Validation\Rules; |
|
13
|
|
|
|
|
14
|
|
|
class Issn extends AbstractRule |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* Check if the current value is a valid International Standard Serial Number (ISSN). |
|
18
|
|
|
* |
|
19
|
|
|
* @see https://en.wikipedia.org/wiki/International_Standard_Serial_Number |
|
20
|
|
|
* |
|
21
|
|
|
* @credit <a href="https://github.com/Intervention/validation">Intervention/validation - \Intervention\Validation\Rules\Issn</a> |
|
22
|
|
|
* |
|
23
|
|
|
* @param mixed $value |
|
24
|
|
|
*/ |
|
25
|
|
|
public function check($value): bool |
|
26
|
|
|
{ |
|
27
|
2 |
|
return preg_match('/^[0-9]{4}-[0-9]{3}[0-9xX]$/', $value) && $this->checkSumMatches($value); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Determine if checksum matches |
|
32
|
|
|
*/ |
|
33
|
|
|
private function checkSumMatches(string $value): bool |
|
34
|
|
|
{ |
|
35
|
2 |
|
return $this->calculateChecksum($value) === $this->parseChecksum($value); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* Calculate checksum from the current value |
|
40
|
|
|
*/ |
|
41
|
|
|
private function calculateChecksum(string $value): int |
|
42
|
|
|
{ |
|
43
|
2 |
|
$checksum = 0; |
|
44
|
2 |
|
$issn_numbers = str_replace('-', '', $value); |
|
45
|
|
|
|
|
46
|
|
|
foreach (range(8, 2) as $num => $multiplicator) { |
|
47
|
2 |
|
$checksum += (int) ($issn_numbers[$num]) * $multiplicator; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
2 |
|
$remainder = ($checksum % 11); |
|
51
|
|
|
|
|
52
|
2 |
|
return $remainder === 0 ? 0 : 11 - $remainder; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Parse attached checksum of current value (last digit) |
|
57
|
|
|
*/ |
|
58
|
|
|
private function parseChecksum(string $value): int |
|
59
|
|
|
{ |
|
60
|
2 |
|
$last = substr($value, -1); |
|
61
|
|
|
|
|
62
|
2 |
|
return strtolower($last) === 'x' ? 10 : (int) $last; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|