Passed
Push — main ( 52de70...4bac34 )
by Breno
02:11
created

ValidationException::addError()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 6
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Exception;
5
6
use Exception;
7
8
class ValidationException extends Exception implements ValidationExceptionInterface
9
{
10
    private array $errors = [];
11
12
    public function formatMessage(): string
13
    {
14
        $messages = [];
15
        foreach ($this->errors as $fieldName => $error) {
16
            foreach ($error->getErrors() as $errorForField) {
17
                $messages[] = "\t - `$fieldName`: $errorForField";
18
            }
19
        }
20
21
        return $this->getMessage() . ":" . PHP_EOL . implode(PHP_EOL, $messages);
22
    }
23
24
    /**
25
     * @inheritDoc
26
     */
27
    public function addError(string $error, ?string $field = null): void
28
    {
29
        if ($field !== null) {
30
            $this->errors[$field][] = $error;
31
        } else {
32
            $this->errors[] = $error;
33
        }
34
    }
35
36
    /**
37
     * @inheritDoc
38
     */
39
    public function getErrors(): array
40
    {
41
        return $this->errors;
42
    }
43
}
44