Completed
Push — master ( e98ae3...0e888f )
by Matt
02:50
created

MultipleOf::validate()   B

Complexity

Conditions 3
Paths 3

Duplication

Lines 0
Ratio 0 %

Size

Total Lines 24
Code Lines 15

Code Coverage

Tests 16
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 15
nc 3
nop 3
dl 0
loc 24
ccs 16
cts 16
cp 1
crap 3
rs 8.9713
c 0
b 0
f 0
1
<?php
2
3
namespace League\JsonGuard\Constraints;
4
5
use League\JsonGuard;
6
use League\JsonGuard\Assert;
7
use League\JsonGuard\ValidationError;
8
9
class MultipleOf implements PropertyConstraint
10
{
11
    const KEYWORD = 'multipleOf';
12
13
    /**
14
     * {@inheritdoc}
15
     */
16 8
    public static function validate($value, $multiple, $pointer = null)
17
    {
18 8
        Assert::type($multiple, 'number', self::KEYWORD, $pointer);
19 6
        Assert::nonNegative($multiple, self::KEYWORD, $pointer);
20
21 4
        if (!is_numeric($value)) {
22 4
            return null;
23
        }
24
25
        // for some reason fmod does not return 0 for cases like fmod(0.0075,0.0001) so I'm doing this manually.
26 4
        $quotient = $value / $multiple;
27 4
        $mod      = $quotient - floor($quotient);
28 4
        if ($mod == 0) {
29 4
            return null;
30
        }
31
32 4
        return new ValidationError(
33 4
            'Number {value} is not a multiple of {multiple_of}',
34 4
            self::KEYWORD,
35 4
            $value,
36 4
            $pointer,
37 4
            ['value' => $value, 'multiple_of' => $multiple]
38 4
        );
39
    }
40
}
41