Completed
Pull Request — master (#108)
by Matt
11:28
created

MultipleOf   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 44
ccs 16
cts 16
cp 1
rs 10
c 0
b 0
f 0
wmc 4
lcom 1
cbo 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 23 3
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 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->getPointer());
32 4
        Assert::nonNegative($parameter, self::KEYWORD, $validator->getPointer());
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 new ValidationError(
45
            'Number {value} is not a multiple of {multiple_of}',
46
            self::KEYWORD,
47
            $value,
48
            $validator->getPointer(),
49
            ['value' => $value, 'multiple_of' => $parameter]
50
        );
51
    }
52
}
53