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 (false !== $json && \is_string($text)) { |
64
|
|
|
$json = self::transformTextToArray($text); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return $json; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* {@inheritdoc} |
72
|
|
|
*/ |
73
|
|
|
public function getParent() |
74
|
|
|
{ |
75
|
|
|
return TextareaType::class; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @param string $text |
80
|
|
|
* |
81
|
|
|
* @return array |
82
|
|
|
*/ |
83
|
|
|
private static function transformTextToArray(string $text): array |
84
|
|
|
{ |
85
|
|
|
$json = []; |
86
|
|
|
foreach (explode("\n", $text) as $keyValue) { |
87
|
|
|
$parts = explode(':', $keyValue); |
88
|
|
|
if (2 === \count($parts)) { |
89
|
|
|
$key = trim($parts[0]); |
90
|
|
|
$value = trim($parts[1]); |
91
|
|
|
|
92
|
|
|
if ($key || $value) { |
93
|
|
|
$json[$key] = $value; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
|
98
|
|
|
return $json; |
99
|
|
|
} |
100
|
|
|
} |
101
|
|
|
|