Passed
Push — master ( d8182e...614f25 )
by Paweł
03:01
created

ValidatorAdapter::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 12
rs 10
ccs 8
cts 8
cp 1
crap 2
1
<?php
2
/**
3
 * Copyright (c) 2020.
4
 * @author Paweł Antosiak <[email protected]>
5
 */
6
7
declare(strict_types=1);
8
9
namespace Gorynych\Adapter;
10
11
use Cake\Collection\Collection;
12
use Gorynych\Resource\Dto\EntityViolation;
13
use Gorynych\Resource\Exception\InvalidEntityException;
14
use Symfony\Component\Config\FileLocatorInterface;
15
use Symfony\Component\Validator\ConstraintViolationInterface;
16
use Symfony\Component\Validator\Validation;
17
use Symfony\Component\Validator\Validator\ValidatorInterface;
18
19
class ValidatorAdapter
20
{
21
    protected ValidatorInterface $validator;
22
    protected FileLocatorInterface $configLocator;
23
24
    public function __construct(FileLocatorInterface $configLocator)
25
    {
26
        $this->configLocator = $configLocator;
27
    }
28
29
    /**
30
     * Validates provided entity object
31
     *
32
     * @param object $entity
33
     * @throws InvalidEntityException if entity is not valid
34
     */
35 1
    public function validate(object $entity): void
36
    {
37 1
        $errors = $this->validator->validate($entity);
38
39 1
        if ($errors->count() > 0) {
40 1
            $violations = (new Collection($errors))->map(
41 1
                static function (ConstraintViolationInterface $violation): EntityViolation {
42 1
                    return new EntityViolation($violation->getPropertyPath(), $violation->getMessage());
43 1
                }
44
            );
45
46 1
            throw InvalidEntityException::fromViolations(...$violations->toList());
47
        }
48
    }
49
50
    /**
51
     * Setups validator
52
     *
53
     * @param string $constraint Constraint name to validate against
54
     * @return self
55
     */
56
    public function setup(string $constraint): self
57
    {
58
        $constraintPath = $this->configLocator->locate("validator/{$constraint}.yaml");
59
60
        $this->validator = Validation::createValidatorBuilder()
61
            ->addYamlMapping($constraintPath)
0 ignored issues
show
Bug introduced by
It seems like $constraintPath can also be of type array; however, parameter $path of Symfony\Component\Valida...ilder::addYamlMapping() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

61
            ->addYamlMapping(/** @scrutinizer ignore-type */ $constraintPath)
Loading history...
62
            ->getValidator();
63
64
        return $this;
65
    }
66
}
67