Test Setup Failed
Push — main ( c2f1dd...5e437f )
by Fractal
11:05
created

ValidationException::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FRZB\Component\RequestMapper\Exception;
6
7
use Fp\Collections\ArrayList;
8
use FRZB\Component\RequestMapper\Data\ErrorInterface as Error;
9
use FRZB\Component\RequestMapper\Data\ValidationError;
10
use JetBrains\PhpStorm\Pure;
11
use Symfony\Component\Validator\ConstraintViolationInterface as ConstraintViolation;
12
use Symfony\Component\Validator\ConstraintViolationListInterface as ConstraintViolationList;
13
14
final class ValidationException extends \LogicException
15
{
16
    public const DEFAULT_MESSAGE = 'Validation error';
17
18
    #[Pure]
19
    private function __construct(
20 4
        private readonly ArrayList $errors,
21
    ) {
22
        parent::__construct(self::DEFAULT_MESSAGE);
23 4
    }
24 4
25 4
    /** @noinspection PhpParamsInspection */
26
    public static function fromConstraintViolationList(ConstraintViolationList $violationList): self
27
    {
28 2
        return self::fromConstraintViolations(...$violationList);
29
    }
30 2
31
    public static function fromConstraintViolations(ConstraintViolation ...$violations): self
32
    {
33 2
        return new self(ArrayList::collect($violations)->map(ValidationError::fromConstraint(...)));
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ')' on line 33 at column 96
Loading history...
34
    }
35 2
36
    public static function fromErrors(Error ...$errors): self
37
    {
38 4
        return new self(ArrayList::collect($errors));
39
    }
40
41 4
    #[Pure]
42
    public function getErrors(): ArrayList
43
    {
44
        return $this->errors->toArrayList();
45 3
    }
46
47 3
    public function getFormattedErrors(): array
48
    {
49
        return $this->errors
50
            ->map(static fn (Error $error) => [$error->getField() => $error->getMessage()])
51
            ->reduce(static fn (array $prev, array $next) => [...$prev, ...$next])
52
            ->getOrElse([])
53
        ;
54
    }
55
}
56