Passed
Push — master ( 27762c...f0b71d )
by Andreas
19:35
created

callback::validate()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 6.6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 1
b 0
f 0
nc 5
nop 2
dl 0
loc 12
ccs 6
cts 10
cp 0.6
crap 6.6
rs 9.6111
1
<?php
2
/**
3
 * @copyright CONTENT CONTROL GmbH, http://www.contentcontrol-berlin.de
4
 */
5
6
namespace midcom\datamanager\validation;
7
8
use Symfony\Component\Validator\Context\ExecutionContextInterface;
9
use midcom\datamanager\storage\container\container;
10
11
class callback
12
{
13
    private $validation;
14
15 19
    public function __construct(array $validation)
16
    {
17 19
        $this->validation = $validation;
18 19
    }
19
20 8
    public function validate($payload, ExecutionContextInterface $context)
21
    {
22 8
        foreach ($this->validation as $entry) {
23 8
            if (!empty($entry['callback'])) {
24 8
                $form = $context->getObject();
25 8
                $result = $entry['callback']($this->to_array($form->getData()));
26 8
                if (is_array($result)) {
27
                    foreach ($result as $field => $message) {
28
                        $context
29
                            ->buildViolation($message)
30
                            ->atPath('[' . $field . ']')
31
                            ->addViolation();
32
                    }
33
                }
34
            }
35
        }
36 8
    }
37
38
    /**
39
     * @param container|array $container
40
     * @return array
41
     */
42 8
    private function to_array($container) : array
43
    {
44 8
        if (is_array($container)) {
45
            // This is a newly added subform, not yet saved, so it's already in view format
46
            return $container;
47
        }
48 8
        $data = [];
49
50 8
        foreach ($container as $field => $value) {
51 8
            $data[$field] = $value->get_value();
52
        }
53
54 8
        return $data;
55
    }
56
}
57