This repository was archived by the owner on May 10, 2019. It is now read-only.
File tree 1 file changed +74
-0
lines changed
1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ <?php
2
+
3
+ namespace Xthiago \FormExtraBundle \Form \DataTransformer ;
4
+
5
+ use Symfony \Component \Form \DataTransformerInterface ;
6
+ use Symfony \Component \Form \Exception \TransformationFailedException ;
7
+
8
+ /**
9
+ * Transforms between a JSON string and an associative array.
10
+ *
11
+ * @author Thiago Rodrigues <xthiago@gmail.com>
12
+ */
13
+ class ArrayToJsonTransformer implements DataTransformerInterface
14
+ {
15
+ /**
16
+ * Constructor
17
+ *
18
+ */
19
+ public function __construct ()
20
+ {
21
+ }
22
+
23
+ /**
24
+ * Transforms an array into a JSON string
25
+ *
26
+ * @param array $array Array to transform
27
+ *
28
+ * @return string
29
+ *
30
+ * @throws TransformationFailedException If the given value is not an array
31
+ */
32
+ public function transform ($ array )
33
+ {
34
+ if (null === $ array ) {
35
+ return '' ;
36
+ }
37
+
38
+ if (!is_array ($ array )) {
39
+ throw new TransformationFailedException ('Expected an array. ' );
40
+ }
41
+
42
+ $ string = json_encode ($ array );
43
+
44
+ return $ string ;
45
+ }
46
+
47
+ /**
48
+ * Transforms a JSON string into an array
49
+ *
50
+ * @param string $string String to transform
51
+ *
52
+ * @return array
53
+ *
54
+ * @throws TransformationFailedException If the given value is not a string
55
+ */
56
+ public function reverseTransform ($ string )
57
+ {
58
+ if (null !== $ string && !is_string ($ string )) {
59
+ throw new TransformationFailedException ('Expected a string. ' );
60
+ }
61
+
62
+ if (empty ($ string )) {
63
+ return array ();
64
+ }
65
+
66
+ $ values = json_decode ($ string , true );
67
+
68
+ if (0 === count ($ values )) {
69
+ return array ();
70
+ }
71
+
72
+ return $ values ;
73
+ }
74
+ }
You can’t perform that action at this time.
0 commit comments