-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathLuhnChecksum.php
More file actions
46 lines (36 loc) · 1.17 KB
/
Copy pathLuhnChecksum.php
File metadata and controls
46 lines (36 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
declare(strict_types=1);
namespace App\PIM\Symbol\Format\Checksum;
use Ibexa\Contracts\ProductCatalog\Values\AttributeDefinitionInterface;
use Ibexa\Contracts\ProductCatalogSymbolAttribute\Value\ChecksumInterface;
final class LuhnChecksum implements ChecksumInterface
{
public function validate(AttributeDefinitionInterface $attributeDefinition, string $value): bool
{
$digits = $this->getDigits($value);
$count = count($digits);
$total = 0;
for ($i = $count - 2; $i >= 0; $i -= 2) {
$digit = $digits[$i];
if ($i % 2 === 0) {
$digit *= 2;
}
$total += $digit > 9 ? $digit - 9 : $digit;
}
$checksum = $digits[$count - 1];
return $total + $checksum === 0;
}
/**
* Returns an array of digits from the given value (skipping any formatting characters).
*
* @return int[]
*/
private function getDigits(string $value): array
{
$chars = array_filter(
str_split($value),
static fn (string $char): bool => $char !== '-'
);
return array_map('intval', array_values($chars));
}
}