Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
CreditCard
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
100.00% covered (success)
100.00%
1 / 1
 isValid
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
1<?php
2/**
3 * Jingga
4 *
5 * PHP Version 8.1
6 *
7 * @package   phpOMS\Validation\Finance
8 * @copyright Dennis Eichhorn
9 * @license   OMS License 2.0
10 * @version   1.0.0
11 * @link      https://jingga.app
12 */
13declare(strict_types=1);
14
15namespace phpOMS\Validation\Finance;
16
17use phpOMS\Validation\ValidatorAbstract;
18
19/**
20 * Credit card validation
21 *
22 * @package phpOMS\Validation\Finance
23 * @license OMS License 2.0
24 * @link    https://jingga.app
25 * @since   1.0.0
26 */
27final class CreditCard extends ValidatorAbstract
28{
29    /**
30     * {@inheritdoc}
31     */
32    public static function isValid($value, array $constraints = null) : bool
33    {
34        if (!\is_string($value)) {
35            return false;
36        }
37
38        $value = \preg_replace('/\D/', '', $value) ?? '';
39
40        // Set the string length and parity
41        $numberLength = \strlen($value);
42        $parity       = $numberLength % 2;
43
44        // Loop through each digit and do the maths
45        $total = 0;
46        for ($i = 0; $i < $numberLength; ++$i) {
47            $digit = (int) $value[$i];
48            // Multiply alternate digits by two
49            if ($i % 2 === $parity) {
50                $digit *= 2;
51                // If the sum is two digits, add them together (in effect)
52                if ($digit > 9) {
53                    $digit -= 9;
54                }
55            }
56            // Total up the digits
57            $total += $digit;
58        }
59
60        // If the total mod 10 equals 0, the value is valid
61        return $total % 10 === 0;
62    }
63}