Completed
Pull Request — master (#108)
by Matt
04:36
created

MultipleOf::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace League\JsonGuard\Constraints;
4
5
use League\JsonGuard\Assert;
6
use League\JsonGuard\ValidationError;
7
use League\JsonGuard\Validator;
8
9
class MultipleOf implements Constraint
10
{
11
    const KEYWORD = 'multipleOf';
12
13
    /**
14
     * @var int|null
15
     */
16
    private $precision;
17
18
    /**
19
     * @param int|null $precision
20
     */
21 6
    public function __construct($precision = 10)
22
    {
23 6
        $this->precision = $precision;
24 6
    }
25
26
    /**
27
     * {@inheritdoc}
28
     */
29 6
    public function validate($value, $parameter, Validator $validator)
30
    {
31 6
        Assert::type($parameter, 'number', self::KEYWORD, $validator->getPointer());
32 4
        Assert::nonNegative($parameter, self::KEYWORD, $validator->getPointer());
33
34 2
        if (!is_numeric($value)) {
35 2
            return null;
36
        }
37
38 2
        $quotient = bcdiv($value, $parameter, $this->precision);
39 2
        $mod      = bcsub($quotient, floor($quotient), $this->precision);
40 2
        if (bccomp($mod, 0, $this->precision) === 0) {
41 2
            return null;
42
        }
43
44 2
        return new ValidationError(
45 2
            'Number {value} is not a multiple of {multiple_of}',
46 2
            self::KEYWORD,
47 2
            $value,
48 2
            $validator->getPointer(),
49 2
            ['value' => $value, 'multiple_of' => $parameter]
50 2
        );
51
    }
52
}
53