Passed
Push — master ( ec0d02...c0f595 )
by Jan
06:31 queued 10s
created

ValidRangeValidator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 29
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 19 6
A __construct() 0 3 1
1
<?php
2
/**
3
 * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
4
 *
5
 * Copyright (C) 2019 - 2020 Jan Böhmer (https://github.com/jbtronics)
6
 *
7
 * This program is free software: you can redistribute it and/or modify
8
 * it under the terms of the GNU Affero General Public License as published
9
 * by the Free Software Foundation, either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License
18
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
namespace App\Validator\Constraints\Misc;
22
23
24
use App\Services\Misc\RangeParser;
25
use Symfony\Component\Validator\Constraint;
26
use Symfony\Component\Validator\ConstraintValidator;
27
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
28
use Symfony\Component\Validator\Exception\UnexpectedValueException;
29
30
class ValidRangeValidator extends ConstraintValidator
31
{
32
33
    protected $rangeParser;
34
35
    public function __construct(RangeParser $rangeParser)
36
    {
37
        $this->rangeParser = $rangeParser;
38
    }
39
40
    public function validate($value, Constraint $constraint)
41
    {
42
        if (!$constraint instanceof ValidRange) {
43
            throw new UnexpectedTypeException($constraint, ValidRange::class);
44
        }
45
46
        // custom constraints should ignore null and empty values to allow
47
        // other constraints (NotBlank, NotNull, etc.) take care of that
48
        if (null === $value || '' === $value) {
49
            return;
50
        }
51
52
        if (!is_string($value)) {
53
            throw new UnexpectedValueException($value, 'string');
54
        }
55
56
        if(!$this->rangeParser->isValidRange($value)) {
57
            $this->context->buildViolation($constraint->message)
58
                ->addViolation();
59
        }
60
    }
61
}