FieldNameValidator::validate()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 17
rs 9.6111
cc 5
nc 5
nop 2
1
<?php declare(strict_types=1);
2
3
namespace Mgid\Component\Pagination\Validator;
4
5
use Symfony\Component\Validator\Exception;
6
use Symfony\Component\Validator\Constraint;
7
use Symfony\Component\Validator\ConstraintValidator;
8
use Mgid\Component\Pagination\InputInterface;
9
10
final class FieldNameValidator extends ConstraintValidator
11
{
12
    /**
13
     * {@inheritdoc}
14
     */
15
    public function validate($input, Constraint $constraint): void
16
    {
17
        if (!$constraint instanceof FieldName) {
18
            throw new Exception\UnexpectedTypeException($constraint, FieldName::class); // @codeCoverageIgnore
19
        }
20
21
        if (!$input instanceof InputInterface) {
22
            throw new Exception\UnexpectedTypeException($input, InputInterface::class); // @codeCoverageIgnore
23
        }
24
25
        foreach ($this->getFields($input) as $fieldName) {
26
            if (!\preg_match($constraint->pattern, $fieldName)) {
27
                $this->context
28
                    ->buildViolation($constraint->message)
29
                    ->atPath($fieldName)
30
                    ->setParameter('{{ field }}', $fieldName)
31
                    ->addViolation();
32
            }
33
        }
34
    }
35
36
    /**
37
     * @param InputInterface $input
38
     *
39
     * @return string[]
40
     */
41
    private function getFields(InputInterface $input): array
42
    {
43
        return \array_merge(
44
            \array_keys($input->getOrders()),
45
            \array_keys($input->getFilters())
46
        );
47
    }
48
}
49