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
|
|
|
public function buildForm(FormBuilderInterface $builder, array $options): void |
22
|
|
|
{ |
23
|
|
|
$builder->addModelTransformer($this); |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
public function transform($json): string |
27
|
|
|
{ |
28
|
|
|
if (null === $json) { |
29
|
|
|
return ''; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
if (!\is_array($json)) { |
33
|
|
|
$json = json_decode($json, true); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
$text = ''; |
37
|
|
|
if (\is_array($json)) { |
38
|
|
|
foreach ($json as $key => $value) { |
39
|
|
|
$text .= trim($key).': '.trim($value)."\r\n"; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return $text; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function reverseTransform($text): array |
47
|
|
|
{ |
48
|
|
|
if (null === $text) { |
49
|
|
|
return []; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$json = json_decode($text, true); |
53
|
|
|
|
54
|
|
|
if (false !== $json && \is_string($text)) { |
55
|
|
|
$json = self::transformTextToArray($text); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $json; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
public function getParent() |
62
|
|
|
{ |
63
|
|
|
return TextareaType::class; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
private static function transformTextToArray(string $text): array |
67
|
|
|
{ |
68
|
|
|
$json = []; |
69
|
|
|
foreach (explode("\n", $text) as $keyValue) { |
70
|
|
|
$parts = explode(':', $keyValue); |
71
|
|
|
if (2 === \count($parts)) { |
72
|
|
|
$key = trim($parts[0]); |
73
|
|
|
$value = trim($parts[1]); |
74
|
|
|
|
75
|
|
|
if ('' !== $key || '' !== $value) { |
76
|
|
|
$json[$key] = $value; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return $json; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|