Completed
Pull Request — master (#93)
by Sullivan
01:59
created

CreditCard::validate()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 38
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 2 Features 0
Metric Value
c 5
b 2
f 0
dl 0
loc 38
rs 5.3846
cc 8
eloc 20
nc 12
nop 1
1
<?php
2
3
namespace IsoCodes;
4
5
/**
6
 * Class CreditCard.
7
 */
8
class CreditCard implements IsoCodeInterface
9
{
10
    /**
11
     * Credit Card validator.
12
     *
13
     * @param string $creditCard
14
     *
15
     * @return bool
16
     */
17
    public static function validate($creditCard)
18
    {
19
        if (!is_string($creditCard) && !empty($creditCard)) {
20
            @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
21
                'Passing other values than a string on '.__METHOD__.' is deprecated since version 2.2.'
22
                .' It will be considered as invalid on version 3.0.',
23
                E_USER_DEPRECATED
24
            );
25
        }
26
27
        // Add !is_string($creditCard) to the condition on 3.0.
28
        if (trim($creditCard) === '') {
29
            return false;
30
        }
31
32
        if (!boolval(preg_match('/.*[1-9].*/', $creditCard))) {
33
            return false;
34
        }
35
36
        //longueur de la chaine $creditCard
37
        $length = strlen($creditCard);
38
39
        //resultat de l'addition de tous les chiffres
40
        $tot = 0;
41
        for ($i = $length - 1; $i >= 0; --$i) {
42
            $digit = substr($creditCard, $i, 1);
43
44
            if ((($length - $i) % 2) == 0) {
45
                $digit = $digit * 2;
46
                if ($digit > 9) {
47
                    $digit = $digit - 9;
48
                }
49
            }
50
            $tot += (int) $digit;
51
        }
52
53
        return ($tot % 10) == 0;
54
    }
55
}
56