Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
CreditCard
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
8
100.00% covered (success)
100.00%
1 / 1
 evaluate
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
8
1<?php
2/**
3 * Pop PHP Framework (http://www.popphp.org/)
4 *
5 * @link       https://github.com/popphp/popphp-framework
6 * @author     Nick Sagona, III <dev@nolainteractive.com>
7 * @copyright  Copyright (c) 2009-2024 NOLA Interactive, LLC. (http://www.nolainteractive.com)
8 * @license    http://www.popphp.org/license     New BSD License
9 */
10
11/**
12 * @namespace
13 */
14namespace Pop\Validator;
15
16/**
17 * Credit card validator class
18 *
19 * @category   Pop
20 * @package    Pop\Validator
21 * @author     Nick Sagona, III <dev@nolainteractive.com>
22 * @copyright  Copyright (c) 2009-2024 NOLA Interactive, LLC. (http://www.nolainteractive.com)
23 * @license    http://www.popphp.org/license     New BSD License
24 * @version    4.0.0
25 */
26class CreditCard extends AbstractValidator
27{
28
29    /**
30     * Method to evaluate the validator
31     *
32     * @param  mixed $input
33     * @return bool
34     */
35    public function evaluate(mixed $input = null): bool
36    {
37        // Set the input, if passed
38        if ($input !== null) {
39            $this->input = $input;
40            if (str_contains((string)$this->input, ' ')) {
41                $this->input = str_replace(' ', '', $this->input);
42            }
43            if (str_contains((string)$this->input, '-')) {
44                $this->input = str_replace('-', '', $this->input);
45            }
46        }
47
48        // Set the default message
49        if ($this->message === null) {
50            $this->message = 'The value must be a valid credit card number.';
51        }
52
53        // Evaluate the input against the validator
54        $nums   = str_split((string)$this->input);
55        $check  = $nums[count($nums) - 1];
56        $start  = count($nums) - 2;
57        $sum    = 0;
58        $double = true;
59
60        for ($i = $start; $i >= 0; $i--) {
61            if ($double) {
62                $num = $nums[$i] * 2;
63                if ($num > 9) {
64                    $num = (int)substr($num, 0, 1) + (int)substr($num, 1, 1);
65                }
66                $sum += $num;
67                $double = false;
68            } else {
69                $sum += $nums[$i];
70                $double = true;
71            }
72        }
73
74        $sum += $check;
75        $rem = $sum % 10;
76
77        return ($rem == 0);
78    }
79
80}