Completed
Pull Request — master (#743)
by Asmir
07:41
created

FormErrorHandler::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
/*
4
 * Copyright 2016 Johannes M. Schmitt <[email protected]>
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace JMS\Serializer\Handler;
20
21
use JMS\Serializer\GraphNavigatorInterface;
22
use JMS\Serializer\JsonSerializationVisitor;
23
use JMS\Serializer\SerializationVisitorInterface;
24
use JMS\Serializer\XmlSerializationVisitor;
25
use JMS\Serializer\YamlSerializationVisitor;
26
use Symfony\Component\Form\Form;
27
use Symfony\Component\Form\FormError;
28
use Symfony\Component\Translation\TranslatorInterface;
29
30
final class FormErrorHandler implements SubscribingHandlerInterface
31
{
32
    private $translator;
33
34
    private $translationDomain;
35
36 351
    public static function getSubscribingMethods()
37
    {
38 351
        $methods = array();
39 351
        foreach (array('xml', 'json', 'yml') as $format) {
40 351
            $methods[] = array(
41 351
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
42 351
                'type' => 'Symfony\Component\Form\Form',
43 351
                'format' => $format,
44
            );
45 351
            $methods[] = array(
46 351
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
47 351
                'type' => 'Symfony\Component\Form\FormError',
48 351
                'format' => $format,
49
            );
50
        }
51
52 351
        return $methods;
53
    }
54
55 359
    public function __construct(TranslatorInterface $translator = null, $translationDomain = 'validators')
56
    {
57 359
        $this->translator = $translator;
58 359
        $this->translationDomain = $translationDomain;
59 359
    }
60
61 1
    public function serializeFormToXml(XmlSerializationVisitor $visitor, Form $form, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
62
    {
63 1
        $formNode = $visitor->getDocument()->createElement('form');
64
65 1
        $formNode->setAttribute('name', $form->getName());
66
67 1
        $formNode->appendChild($errorsNode = $visitor->getDocument()->createElement('errors'));
68 1
        foreach ($form->getErrors() as $error) {
69 1
            $errorNode = $visitor->getDocument()->createElement('entry');
70 1
            $errorNode->appendChild($this->serializeFormErrorToXml($visitor, $error, array()));
0 ignored issues
show
Bug introduced by
It seems like $error defined by $error on line 68 can also be of type object<Symfony\Component\Form\FormErrorIterator>; however, JMS\Serializer\Handler\F...rializeFormErrorToXml() does only seem to accept object<Symfony\Component\Form\FormError>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
71 1
            $errorsNode->appendChild($errorNode);
72
        }
73
74 1
        foreach ($form->all() as $child) {
75 1
            if ($child instanceof Form) {
76 1
                if (null !== $node = $this->serializeFormToXml($visitor, $child, array())) {
77 1
                    $formNode->appendChild($node);
78
                }
79
            }
80
        }
81
82 1
        return $formNode;
83
    }
84
85 5
    public function serializeFormToJson(JsonSerializationVisitor $visitor, Form $form, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
86
    {
87 5
        return $this->convertFormToArray($visitor, $form);
88
    }
89
90
    public function serializeFormToYml(YamlSerializationVisitor $visitor, Form $form, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
91
    {
92
        return $this->convertFormToArray($visitor, $form);
93
    }
94
95 2
    public function serializeFormErrorToXml(XmlSerializationVisitor $visitor, FormError $formError, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
96
    {
97 2
        return $visitor->getDocument()->createCDATASection($this->getErrorMessage($formError));
98
    }
99
100 1
    public function serializeFormErrorToJson(JsonSerializationVisitor $visitor, FormError $formError, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
101
    {
102 1
        return $this->getErrorMessage($formError);
103
    }
104
105
    public function serializeFormErrorToYml(YamlSerializationVisitor $visitor, FormError $formError, array $type)
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
106
    {
107
        return $this->getErrorMessage($formError);
108
    }
109
110 11
    private function getErrorMessage(FormError $error)
111
    {
112
113 11
        if ($this->translator === null){
114 1
            return $error->getMessage();
115
        }
116
117 10
        if (null !== $error->getMessagePluralization()) {
118 2
            return $this->translator->transChoice($error->getMessageTemplate(), $error->getMessagePluralization(), $error->getMessageParameters(), $this->translationDomain);
119
        }
120
121 8
        return $this->translator->trans($error->getMessageTemplate(), $error->getMessageParameters(), $this->translationDomain);
122
    }
123
124 5
    private function convertFormToArray(SerializationVisitorInterface $visitor, Form $data)
125
    {
126 5
        $form = new \ArrayObject();
127 5
        $errors = array();
128 5
        foreach ($data->getErrors() as $error) {
129 4
            $errors[] = $this->getErrorMessage($error);
0 ignored issues
show
Bug introduced by
It seems like $error defined by $error on line 128 can also be of type object<Symfony\Component\Form\FormErrorIterator>; however, JMS\Serializer\Handler\F...dler::getErrorMessage() does only seem to accept object<Symfony\Component\Form\FormError>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
130
        }
131
132 5
        if ($errors) {
0 ignored issues
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...
133 4
            $form['errors'] = $errors;
134
        }
135
136 5
        $children = array();
137 5
        foreach ($data->all() as $child) {
138 2
            if ($child instanceof Form) {
139 2
                $children[$child->getName()] = $this->convertFormToArray($visitor, $child);
140
            }
141
        }
142
143 5
        if ($children) {
0 ignored issues
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...
144 2
            $form['children'] = $children;
145
        }
146
147 5
        return $form;
148
    }
149
}
150