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

MultipleOf   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A validate() 0 17 3
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