Skip to content

Commit

Permalink
Merge 42af95b into 15566a4
Browse files Browse the repository at this point in the history
  • Loading branch information
Andres Galindo committed Oct 16, 2016
2 parents 15566a4 + 42af95b commit 381eeb4
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
6 changes: 6 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- [`string.ip()`](#stringip)
- [`string.uri($options)`](#stringurioptions)
- [`string.replace($pattern, $replacement)`](#stringreplacepattern-replacement)
- [`string.creditCard()`](#stringcreditcard)
- [`date`](#date)
- [`date.iso()`](#dateiso)
- [`date.format($format)`](#dateformatformat)
Expand Down Expand Up @@ -137,6 +138,11 @@ Replace matched portion of string
```php
$schema = cmf()->string()->replace('/\d+/', 'foo');
```
#### string.creditCard()
Validate value is a credit card
```php
$schema = cmf()->string()->creditCard();
```
#### date()
Validates data is a date
```php
Expand Down
25 changes: 25 additions & 0 deletions src/Validator/StringValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,31 @@ public function email()
});
}

/**
* Validate the number is a valid credit card
*
* @return $this
*/
public function creditCard()
{
return $this->add(function ($value, $nameKey) {
$i = strlen($value);
$sum = 0;
$mul = 1;

while ($i--) {
$char = $value[$i] * $mul;
$sum = $sum + ($char - ($char > 9) * 9);
$mul = $mul ^ 3;
}

$check = ($sum % 10 === 0) && ($sum > 0);
if (!$check) {
return $this->createError('string.credit-card', $value, $nameKey);
}
});
}

/**
* Validate the string is an IP
*
Expand Down
33 changes: 33 additions & 0 deletions tests/unit/Validator/StringValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -503,4 +503,37 @@ public function testMapWithCallbackMapper()
$result = $this->stringValidator->__invoke('present');
$this->assertEquals('returned-value', $result);
}

public function getCreditCardNumbers()
{
return [
['378282246310005'],
['371449635398431'],
['378734493671000'],
['5610591081018250'],
['30569309025904'],
['38520000023237'],
['6011111111111117'],
['6011000990139424'],
];
}

/**
* @dataProvider getCreditCardNumbers
*/
public function testIsCreditCard($creditCard)
{
$this->stringValidator->creditCard();
$this->assertTrue(
$this->stringValidator->__invoke($creditCard)
);
}

public function testCreditCardOnInvalidValue()
{
$this->stringValidator->creditCard();
$this->assertFalse(
$this->stringValidator->__invoke('rawr')
);
}
}

0 comments on commit 381eeb4

Please sign in to comment.