Completed
Push — master ( 088fe8...421f0e )
by Andreas
22:30
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
        $result = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $result is dead and can be removed.
Loading history...
23 8
        foreach ($this->validation as $entry) {
24 8
            if (!empty($entry['callback'])) {
25 8
                $form = $context->getRoot();
26
                // hack to get error messages to show up at the correct place (also see below)
27 8
                $context->setNode($form->getData(), $form, null, '');
28 8
                $result = call_user_func($entry['callback'], $this->to_array($form->getData()));
29 8
                if (is_array($result)) {
30
                    foreach ($result as $field => $message) {
31
                        $context
32
                            ->buildViolation($message)
33
                            // There might be a nice way to do this, but I have no idea what it could be...
34
                            ->atPath('children[' . $field . '].data')
35
                            ->addViolation();
36
                    }
37
                }
38
            }
39
        }
40 8
    }
41
42 8
    private function to_array(container $container) : array
43
    {
44 8
        $data = [];
45
46 8
        foreach ($container as $field => $value) {
47 8
            $data[$field] = $value->get_value();
48
        }
49
50 8
        return $data;
51
    }
52
}
53