IpVNValidator   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 6
dl 0
loc 31
c 0
b 0
f 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 13 3
A getCode() 0 11 3
1
<?php
2
/**
3
 * @link https://github.com/vuongxuongminh/symfony-validation
4
 * @copyright Copyright (c) 2019 Vuong Xuong Minh
5
 * @license [MIT](http://www.opensource.org/licenses/MIT)
6
 */
7
8
namespace PHPViet\Symfony\Validation\Constraints;
9
10
use Symfony\Component\Validator\Constraint;
11
use Symfony\Component\Validator\ConstraintValidator;
12
use PHPViet\Validation\Validator as ConcreteValidator;
13
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
14
15
/**
16
 * @author Vuong Minh <[email protected]>
17
 * @since 1.0.0
18
 */
19
class IpVNValidator extends ConstraintValidator
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function validate($value, Constraint $constraint): void
25
    {
26
        if (! $constraint instanceof IpVN) {
27
            throw new UnexpectedTypeException($constraint, IpVN::class);
28
        }
29
30
        if (false === ConcreteValidator::ipVN($constraint->version)->validate($value)) {
31
            $this->context->buildViolation($constraint->message)
32
                ->setParameter('{{ value }}', $this->formatValue($value))
33
                ->setCode($this->getCode($constraint->version))
34
                ->addViolation();
35
        }
36
    }
37
38
    protected function getCode(?int $ipVersion): string
39
    {
40
        switch ($ipVersion) {
41
            case IpVN::IPV4:
42
                return IpVN::IPV4_VN_ERROR;
43
            case IpVN::IPV6:
44
                return IpVN::IPV6_VN_ERROR;
45
            default:
46
                return IpVN::IP_VN_ERROR;
47
        }
48
    }
49
}
50