Passed
Push — master ( 8cc391...1279f5 )
by Daniel
01:37
created

CakeValidationConverter::addSubErrors()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 10
cc 3
nc 3
nop 3
crap 3
1
<?php
2
3
namespace Selective\Validation\Converter;
4
5
use Selective\Validation\ValidationResult;
6
7
/**
8
 * CakePHP validation error convert.
9
 */
10
final class CakeValidationConverter implements ValidationConverterInterface
11
{
12
    /**
13
     * Create validation result from array with errors.
14
     *
15
     * @param array $errors The validation errors
16
     *
17
     * @return ValidationResult The result
18
     */
19 4
    public function createValidationResult($errors): ValidationResult
20
    {
21 4
        $result = new ValidationResult();
22
23 4
        $this->addErrors($result, (array)$errors);
24
25 4
        return $result;
26
    }
27
28
    /**
29
     * Add errors.
30
     *
31
     * @param ValidationResult $result The result
32
     * @param array $errors The errors
33
     * @param string $path The path
34
     *
35
     * @return void
36
     */
37 4
    private function addErrors(ValidationResult $result, array $errors, string $path = ''): void
38
    {
39 4
        foreach ($errors as $field => $error) {
40 4
            $oldPath = $path;
41 4
            $path .= ($path === '' ? '' : '.') . $field;
42 4
            $this->addSubErrors($result, $error, $path);
43 4
            $path = $oldPath;
44
        }
45 4
    }
46
47
    /**
48
     * Add sub errors.
49
     *
50
     * @param ValidationResult $result The result
51
     * @param array $error The error
52
     * @param string $path The path
53
     *
54
     * @return void
55
     */
56 4
    private function addSubErrors(ValidationResult $result, array $error, string $path = ''): void
57
    {
58 4
        foreach ($error as $field2 => $errorMessage) {
59 4
            if (is_array($errorMessage)) {
60 2
                $this->addErrors($result, [$field2 => $errorMessage], $path);
61
            } else {
62 4
                $result->addError($path, $errorMessage);
63
            }
64
        }
65 4
    }
66
}
67