Completed
Pull Request — master (#108)
by Matt
04:36
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 19
cts 19
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
    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