forked from phalcon/incubator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCardNumber.php
118 lines (105 loc) · 3.2 KB
/
CardNumber.php
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<?php
namespace Phalcon\Mvc\Model\Validator;
use Phalcon\Mvc\EntityInterface;
use Phalcon\Mvc\Model\Validator;
use Phalcon\Mvc\Model\ValidatorInterface;
use Phalcon\Mvc\Model\Exception;
/**
* Phalcon\Mvc\Model\Validator\CardNumber
*
* Validates credit card number using Luhn algorithm
*
*<code>
*use Phalcon\Mvc\Model\Validator\CardNumber;
*
*class User extends Phalcon\Mvc\Model
*{
*
* public function validation()
* {
* $this->validate(new CardNumber([
* 'field' => 'cardnumber',
* 'type' => CardNumber::VISA, // Any if not specified
* 'message' => 'Card number must be valid'
* ]));
*
* if ($this->validationHasFailed() == true) {
* return false;
* }
* }
*
*}
*</code>
*/
class CardNumber extends Validator implements ValidatorInterface
{
const AMERICAN_EXPRESS = 0; // 34, 37
const MASTERCARD = 1; // 51-55
const VISA = 2; // 4
/**
* {@inheritdoc}
*
* <strong>NOTE:</strong>
* for Phalcon < 2.0.4 replace
* <code>\Phalcon\Mvc\EntityInterface</code>
* by
* <code>\Phalcon\Mvc\ModelInterface</code>
*
* @param EntityInterface $record
*
* @return bool
* @throws Exception
*/
public function validate(EntityInterface $record)
{
$field = $this->getOption('field');
if (false === is_string($field)) {
throw new Exception('Field name must be a string');
}
$fieldValue = $record->readAttribute($field);
$value = preg_replace('/[^\d]/', '', $fieldValue);
if ($this->isSetOption('type')) {
$type = $this->getOption('type');
switch ($type) {
case CardNumber::AMERICAN_EXPRESS:
$issuer = substr($value, 0, 2);
$result = (true === in_array($issuer, [34, 37]));
break;
case CardNumber::MASTERCARD:
$issuer = substr($value, 0, 2);
$result = (true === in_array($issuer, [51, 52, 53, 54, 55]));
break;
case CardNumber::VISA:
$issuer = $value[0];
$result = ($issuer == 4);
break;
default:
throw new Exception('Incorrect type specifier');
}
if (false === $result) {
$message = $this->getOption('message') ?: 'Credit card number is invalid';
$this->appendMessage($message, $field, "CardNumber");
return false;
}
}
$value = strrev($value);
$checkSum = 0;
for ($i = 0; $i < strlen($value); $i++) {
if (($i % 2) == 0) {
$temp = $value[$i];
} else {
$temp = $value[$i] * 2;
if ($temp > 9) {
$temp -= 9;
}
}
$checkSum += $temp;
}
if (($checkSum % 10) != 0) {
$message = $this->getOption('message') ?: 'Credit card number is invalid';
$this->appendMessage($message, $field, "CardNumber");
return false;
}
return true;
}
}