1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mbright\Validation\Rule\Validate; |
4
|
|
|
|
5
|
|
|
class CreditCard implements ValidateRuleInterface |
6
|
|
|
{ |
7
|
|
|
/** |
8
|
|
|
* Validates the value as a credit card number. |
9
|
|
|
* |
10
|
|
|
* @param object $subject The subject to be filtered. |
11
|
|
|
* @param string $field The subject field name. |
12
|
|
|
* |
13
|
|
|
* @return bool True if valid, false if not. |
14
|
|
|
*/ |
15
|
33 |
|
public function __invoke($subject, string $field): bool |
16
|
|
|
{ |
17
|
|
|
// get the value; remove spaces, dashes, and dots |
18
|
33 |
|
$value = str_replace([' ', '-', '.'], '', (string) $subject->$field); |
19
|
|
|
|
20
|
|
|
// is it composed only of digits? |
21
|
33 |
|
if (!ctype_digit($value)) { |
22
|
12 |
|
return false; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
// luhn mod-10 algorithm: https://gist.github.com/1287893 |
26
|
|
|
$sumTable = [ |
27
|
21 |
|
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], |
28
|
|
|
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9], |
29
|
|
|
]; |
30
|
|
|
|
31
|
21 |
|
$sum = 0; |
32
|
21 |
|
$flip = 0; |
33
|
|
|
|
34
|
21 |
|
for ($i = strlen($value) - 1; $i >= 0; $i--) { |
35
|
21 |
|
$sum += $sumTable[$flip++ & 0x1][$value[$i]]; |
36
|
|
|
} |
37
|
|
|
|
38
|
21 |
|
return $sum % 10 === 0; |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|