Completed
Pull Request — master (#108)
by Matt
59:00
created

MultipleOf::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 2
cts 2
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 function League\JsonGuard\error;
7
use League\JsonGuard\Validator;
8
9
class MultipleOf implements Constraint
10
{
11
    const KEYWORD = 'multipleOf';
12
13
    /**
14
     * @var int|null
15
     */
16 8
    private $precision;
17
18 8
    /**
19 6
     * @param int|null $precision
20
     */
21 4
    public function __construct($precision = 10)
22 4
    {
23
        $this->precision = $precision;
24
    }
25
26 4
    /**
27 4
     * {@inheritdoc}
28 4
     */
29 4
    public function validate($value, $parameter, Validator $validator)
30
    {
31
        Assert::type($parameter, 'number', self::KEYWORD, $validator->getSchemaPath());
32 4
        Assert::nonNegative($parameter, self::KEYWORD, $validator->getSchemaPath());
33 4
34 4
        if (!is_numeric($value)) {
35 4
            return null;
36 4
        }
37 4
38 4
        $quotient = bcdiv($value, $parameter, $this->precision);
39
        $mod      = bcsub($quotient, floor($quotient), $this->precision);
40
        if (bccomp($mod, 0, $this->precision) === 0) {
41
            return null;
42
        }
43
44
        return error('The number must be a multiple of {parameter}.', $validator);
45
    }
46
}
47