Passed
Push — master ( f5fadc...72d313 )
by Christian
02:28
created

JsonType::reverseTransform()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 13
nc 3
nop 1
dl 0
loc 24
rs 8.8333
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * (c) Christian Gripp <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Core23\Form\Type;
13
14
use Symfony\Component\Form\AbstractType;
15
use Symfony\Component\Form\DataTransformerInterface;
16
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
17
use Symfony\Component\Form\FormBuilderInterface;
18
19
final class JsonType extends AbstractType implements DataTransformerInterface
20
{
21
    /**
22
     * {@inheritdoc}
23
     */
24
    public function buildForm(FormBuilderInterface $builder, array $options): void
25
    {
26
        $builder->addModelTransformer($this);
27
    }
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function transform($json)
33
    {
34
        if (null === $json) {
35
            return '';
36
        }
37
38
        if (!\is_array($json)) {
39
            $json = json_decode($json, true);
40
        }
41
42
        $text = '';
43
        if (\is_array($json)) {
44
            foreach ($json as $key => $value) {
45
                $text .= trim($key).': '.trim($value)."\r\n";
46
            }
47
        }
48
49
        return $text;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function reverseTransform($text)
56
    {
57
        if (null === $text) {
58
            return [];
59
        }
60
61
        $json = json_decode($text, true);
62
63
        if (!$json) {
64
            $json = [];
65
            foreach (explode("\n", $text) as $keyValue) {
66
                $parts = explode(':', $keyValue);
67
                if (2 === \count($parts)) {
68
                    $key   = trim($parts[0]);
69
                    $value = trim($parts[1]);
70
71
                    if ($key || $value) {
72
                        $json[$key] = $value;
73
                    }
74
                }
75
            }
76
        }
77
78
        return $json;
79
    }
80
81
    /**
82
     * {@inheritdoc}
83
     */
84
    public function getParent()
85
    {
86
        return TextareaType::class;
87
    }
88
}
89