Passed
Push — main ( 074ebe...9be93f )
by Breno
01:36
created

ParseErrorsTrait::errorsAsArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
nc 3
nop 0
dl 0
loc 12
rs 10
c 1
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Exception;
5
6
use BrenoRoosevelt\Validation\Error;
7
8
trait ParseErrorsTrait
9
{
10
    /** @return Error[] */
11
    abstract public function getErrors(): array;
12
13
    public function errorsAsArray(): array
14
    {
15
        $errors = [];
16
        foreach ($this->getErrors() as $error) {
17
            $errors[] = [
18
                'field' => $error->field(),
19
                'message' => $error->message(),
20
                'type' => $error->rule() ? array_reverse(explode('\\', get_class($error->rule())))[0] : null
21
            ];
22
        }
23
24
        return $errors;
25
    }
26
27
    public function errorsAsString(): string
28
    {
29
        $errors = "";
30
        foreach ($this->errorsAsArray() as $error) {
31
            $errors .= sprintf(
32
                "\t- `%s`: %s [%s]",
33
                $error['field'] ?? '_error',
34
                $error['message'],
35
                $error['type'] ?? ''
36
            ) . PHP_EOL;
37
        }
38
39
        return $errors;
40
    }
41
}
42