Test Failed
Branch release/v3.0.0 (f6f419)
by Anatoly
03:15
created

InvalidEntityException::assertValid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 9
rs 10
1
<?php declare(strict_types=1);
2
3
namespace App\Exception;
4
5
/**
6
 * Import classes
7
 */
8
use Sunrise\Http\Router\Exception\BadRequestException;
9
use Symfony\Component\Validator\Validator\ValidatorInterface;
10
use Symfony\Component\Validator\ConstraintViolationListInterface;
11
12
/**
13
 * Import functions
14
 */
15
use function get_class;
16
17
/**
18
 * InvalidEntityException
19
 */
20
final class InvalidEntityException extends BadRequestException
21
{
22
23
    /**
24
     * Throws the exception if the given entity isn't valid
25
     *
26
     * @param object $entity
27
     * @param ValidatorInterface $validator
28
     *
29
     * @return void
30
     *
31
     * @throws self
32
     */
33
    public static function assertValid(object $entity, ValidatorInterface $validator) : void
34
    {
35
        $violations = self::convertViolationsToArray($validator->validate($entity));
36
        if ([] === $violations) {
37
            return;
38
        }
39
40
        throw new self('Invalid Entity ' . get_class($entity), [
41
            'violations' => $violations,
42
        ]);
43
    }
44
45
    /**
46
     * Converts the given violation list object to array
47
     *
48
     * @param ConstraintViolationListInterface $violations
49
     *
50
     * @return array
51
     */
52
    private static function convertViolationsToArray(ConstraintViolationListInterface $violations) : array
53
    {
54
        $result = [];
55
        foreach ($violations as $violation) {
56
            $result[] = [
57
                'message' => $violation->getMessage(),
58
                'property' => $violation->getPropertyPath(),
59
            ];
60
        }
61
62
        return $result;
63
    }
64
}
65