ValuetoChoiceOrTextTransformer::transform()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace Black\Common\Application\Form\Transformer;
4
5
use Symfony\Component\Form\DataTransformerInterface;
6
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
7
8
/**
9
 * Class ValuetoChoiceOrTextTransformer
10
 *
11
 * ValueToChoiceOrTextTransformer save the content of TextType value if "other" is selected.
12
 * Otherwise, this transformer save the value of the ChoiceType
13
 */
14
class ValuetoChoiceOrTextTransformer implements DataTransformerInterface
15
{
16
    /**
17
     * @var array
18
     */
19
    protected $choices;
20
21
    /**
22
     * Construct the transformer
23
     *
24
     * @param ChoiceListInterface $choices
25
     */
26
    public function __construct(ChoiceListInterface $choices)
27
    {
28
        $this->choices = $choices->getChoices();
29
    }
30
31
    /**
32
     * {@inheritDoc}
33
     */
34
    public function reverseTransform($data)
35
    {
36
        if ('other' === $data['choice']) {
37
            return $data['text'];
38
        }
39
40
        return $data['choice'];
41
    }
42
43
    /**
44
     * {@inheritDoc}
45
     */
46
    public function transform($data)
47
    {
48
        if (in_array($data, $this->choices, true)) {
49
            return ['choice' => $data, 'text' => null];
50
        }
51
52
        return ['choice' => 'other', 'text' => $data];
53
    }
54
}
55