Skip to content

Commit

Permalink
Create php script cards
Browse files Browse the repository at this point in the history
  • Loading branch information
Vlada1356277 authored Feb 20, 2023
0 parents commit 6ba2051
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions cards/php script cards
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

class Validator
{
public static function validate($cardNumber)
{
// удалим ненужное из номера
$cardNumber = preg_replace('/\D/', '', $cardNumber);

// Алгоритм Луна
if (!self::isValidLuhn($cardNumber)) {
return 'невалидная :(';
}

// Виза или Мастеркард?
$эмитент = self::getЭмитент($cardNumber);

// возврат валидации и эмитента
return 'валидная, ' . $эмитент;
}

private static function isValidLuhn($cardNumber)
{
$sum = 0;
$alt = false;
for ($i = strlen($cardNumber) - 1; $i >= 0; $i--) {
$num = intval($cardNumber[$i]);
if ($alt) {
$num *= 2;
if ($num > 9) {
$num = $num % 10 + 1;
}
}
$sum += $num;
$alt = !$alt;
}
return $sum % 10 == 0;
}

private static function getЭмитент($cardNumber)
{
// виза
if (preg_match('/^4[0-9]{12}(?:[0-9]{3})?$/', $cardNumber)) {
return 'Visa';
}

// мастеркард
if (preg_match('/^5[1-5][0-9]{14}$/', $cardNumber)) {
return 'Mastercard';
}

// эмитент не определен
return 'название эмитента не определено';
}
}

$cardNumber = $argv[1];
$result = Validator::validate($cardNumber);
echo $result;

// php try2.php 4111111111111111

0 comments on commit 6ba2051

Please sign in to comment.