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

ValidationException   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 34
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A formatMessage() 0 10 3
A addError() 0 6 2
A getErrors() 0 3 1
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