FormlyFormHandler::getConvertedChild()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 44
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 44
rs 8.439
ccs 26
cts 26
cp 1
cc 5
eloc 33
nc 5
nop 2
crap 5
1
<?php
2
3
namespace Pgs\RestfonyBundle\Handler;
4
5
use JMS\Serializer\GenericSerializationVisitor;
6
use JMS\Serializer\GraphNavigator;
7
use JMS\Serializer\Handler\SubscribingHandlerInterface;
8
use JMS\Serializer\JsonSerializationVisitor;
9
use Symfony\Component\Form\Form;
10
use Symfony\Component\Form\FormError;
11
use Symfony\Component\Routing\RouterInterface;
12
use Symfony\Component\Translation\TranslatorInterface;
13
14
class FormlyFormHandler implements SubscribingHandlerInterface
15
{
16
    private $translator;
17
    /**
18
     * @var RouterInterface
19
     */
20
    private $router;
21
22 1
    public static function getSubscribingMethods()
23
    {
24 1
        $methods = array();
25 1
        foreach (array('xml', 'json', 'yml') as $format) {
26 1
            $methods[] = array(
27 1
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
28
                'type' => Form::class,
29 1
                'format' => $format,
30
            );
31 1
            $methods[] = array(
32 1
                'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
33
                'type' => FormError::class,
34 1
                'format' => $format,
35
            );
36
        }
37
38 1
        return $methods;
39
    }
40
41 5
    public function __construct(TranslatorInterface $translator, RouterInterface $router)
42
    {
43 5
        $this->translator = $translator;
44 5
        $this->router = $router;
45 5
    }
46
47 4
    public function serializeFormToJson(JsonSerializationVisitor $visitor, Form $form)
48
    {
49 4
        return $this->convertFormToArray($visitor, $form);
50
    }
51
52 4
    protected function getErrorMessage(FormError $error)
53
    {
54 4
        if (null !== $error->getMessagePluralization()) {
55 4
            return $this->translator->transChoice(
56 4
                $error->getMessageTemplate(),
57 4
                $error->getMessagePluralization(),
58 4
                $error->getMessageParameters(),
59 4
                'validators'
60
            );
61
        }
62
63 4
        return $this->translator->trans($error->getMessageTemplate(), $error->getMessageParameters(), 'validators');
64
    }
65
66 4
    protected function convertFormToArray(GenericSerializationVisitor $visitor, Form $data)
67
    {
68 4
        $isRoot = null === $visitor->getRoot();
69
70 4
        $form = $errors = array();
71 4
        foreach ($data->getErrors() as $error) {
72 4
            $errors[] = $this->getErrorMessage($error);
1 ignored issue
show
Documentation introduced by
$error is of type object<Symfony\Component...ormErrorIterator>|false, but the function expects a object<Symfony\Component\Form\FormError>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
73
        }
74
75 4
        if ($errors) {
1 ignored issue
show
Bug Best Practice introduced by
The expression $errors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
76 4
            $form['errors'] = $errors;
77
        }
78
79 4
        $children = array();
80 4
        foreach ($data->all() as $child) {
81 4
            if ($child instanceof Form) {
82 4
                $children[$child->getName()] = $this->getConvertedChild($child, $visitor);
83
            }
84
        }
85
86 4
        if ($children) {
1 ignored issue
show
Bug Best Practice introduced by
The expression $children of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
87 4
            $form['children'] = $children;
88
        }
89
90 4
        if ($isRoot) {
91 4
            $visitor->setRoot($form);
92
        }
93
94 4
        return $form;
95
    }
96
97
    /**
98
     * @param Form $child
99
     * @param GenericSerializationVisitor $visitor
100
     * @return array
101
     */
102 4
    private function getConvertedChild(Form $child, GenericSerializationVisitor $visitor)
103
    {
104 4
        if ($child->count()) {
105
            return [
106 4
                'type' => 'multifield',
107 4
                'key' => $child->getName(),
108
                'templateOptions' => [
109 4
                    'fields' => $this->convertFormToArray($visitor, $child),
110
                ],
111
            ];
112
        } else {
113
            $templateOptions = [
114 4
                'label' => $child->getConfig()->getOption('label'),
115 4
                'required' => $child->isRequired(),
116
            ];
117
118 4
            if ($child->getConfig()->getOption('custom-type')) {
119 1
                $textType = $child->getConfig()->getOption('custom-type');
120
            } else {
121 3
                $type = $child->getConfig()->getType();
122 3
                switch ($type->getName()) {
0 ignored issues
show
Bug introduced by
The method getName() does not seem to exist on object<Symfony\Component...olvedFormTypeInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
123 3
                    case 'rest_entity':
124 1
                        $textType = 'select-one';
125 1
                        $templateOptions['autocompleteUrl']
126 1
                            = $this->getAutocompleteUrl($child->getConfig()->getDataClass());
127 1
                        break;
128 2
                    case 'rest_collection':
129 1
                        $textType = 'select-multi';
130 1
                        $templateOptions['autocompleteUrl']
131 1
                            = $this->getAutocompleteUrl($child->getConfig()->getDataClass());
132 1
                        break;
133
                    default:
134 1
                        $textType = 'input';
135 1
                        break;
136
                }
137
            }
138
139
            return [
140 4
                'type' => $textType,
141 4
                'key' => $child->getName(),
142 4
                'templateOptions' => $templateOptions,
143
            ];
144
        }
145
    }
146
147 2
    protected function getAutocompleteUrl($dataclass)
148
    {
149 2
        $entityName = $dataclass;
150
151 2
        $routeName = 'autocomplete_' . strtolower($entityName);
152
153 2
        return $this->router->getRouteCollection()->get($routeName) ? $this->router->generate($routeName) : null;
154
    }
155
}
156