Completed
Push — master ( c2b792...5f7a06 )
by Andreas
16:18
created

callback::to_array()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
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($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->getRoot();
25
                // hack to get error messages to show up at the correct place (also see below)
26 8
                $context->setNode($form->getData(), $form, null, '');
27 8
                $result = call_user_func($entry['callback'], $this->to_array($form->getData()));
28 8
                if (is_array($result)) {
29
                    foreach ($result as $field => $message) {
30
                        $context
31
                            ->buildViolation($message)
32
                            // There might be a nice way to do this, but I have no idea what it could be...
33
                            ->atPath('children[' . $field . '].data')
34
                            ->addViolation();
35
                    }
36
                }
37
            }
38
        }
39 8
    }
40
41 8
    private function to_array(container $container) : array
42
    {
43 8
        $data = [];
44
45 8
        foreach ($container as $field => $value) {
46 8
            $data[$field] = $value->get_value();
47
        }
48
49 8
        return $data;
50
    }
51
}
52