ValidOddNumber::passes()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 2
b 0
f 0
nc 4
nop 2
dl 0
loc 21
rs 9.6111
1
<?php
2
3
namespace Milwad\LaravelValidate\Rules;
4
5
use Illuminate\Contracts\Validation\Rule;
6
7
class ValidOddNumber implements Rule
8
{
9
    /**
10
     * Check number is odd.
11
     */
12
    public function passes($attribute, $value): bool
13
    {
14
        if (! is_numeric($value)) {
15
            return false;
16
        }
17
18
        $number = strval($value);
19
        $number = explode('.', $number);
20
21
        // Check if there is a decimal part and it's not zero
22
        if (isset($number[1]) && $number[1] != 0) {
23
            return false;
24
        }
25
26
        $number = $number[0];
27
28
        if (extension_loaded('gmp')) {
29
            return gmp_cmp(gmp_mod($number, '2'), '0') !== 0;
30
        }
31
32
        return $number % 2 !== 0;
33
    }
34
35
    /**
36
     * Get the validation error message.
37
     */
38
    public function message(): string
39
    {
40
        return __('validate.odd-number');
41
    }
42
}
43