1: <?php
2: namespace TIC\CoreBundle\Form\DataTransformer;
3:
4: use Symfony\Component\Form\DataTransformerInterface;
5: use Symfony\Component\Form\Exception\TransformationFailedException;
6:
7: /**
8: * Transforms between a serialized data (string) and a data structure (mixed).
9: *
10: * Example: store a complex data (form compound) into a simple database column (varchar)
11: */
12: class SerializedTransformer implements DataTransformerInterface
13: {
14: protected $type = "serialize"; /** json | serialize (default) */
15:
16: /**
17: * Construct the data transformer with parameters (type of serialization).
18: *
19: * @param string $type Type of serialization method: json | serialize (default)
20: */
21: public function __construct(string $type = null)
22: {
23: if ($type !== null) $this->type = $type;
24: }
25:
26: /**
27: * Transforms a serialization string into a data structure.
28: *
29: * @param string $values Data serialized (all values into one string)
30: * @return mixed Data structure (array, object, scalar...)
31: * @throws TransformationFailedException If the given value is not a serialization.
32: */
33: public function transform(mixed $values = null): mixed
34: {
35: if ($values === null) return null;
36: # if (! \is_string($values)) return $values;
37: if (! \is_string($values)) throw new TransformationFailedException("Expected a string.");
38:
39: try {
40: switch ($this->type) {
41: case 'json' : return \json_decode($values, true, 512, JSON_THROW_ON_ERROR);
42: default : return \unserialize($values);
43: }
44: } catch (\Exception $e) { throw new TransformationFailedException("Failed to unserialize: ".$e->getMessage());
45: } catch (\TypeError $t) { throw new TransformationFailedException("Failed to unserialize: ".$t->getMessage());
46: }
47: }
48:
49: /**
50: * Transforms a data structure into a serialization string.
51: *
52: * @param mixed $values Data structure (array, object, scalar...)
53: * @return string Data serialized (all values into one string)
54: */
55: public function reverseTransform(mixed $values = null): ?string
56: {
57: if ($values === null) return null;
58:
59: try {
60: switch ($this->type) {
61: case 'json' : return \json_encode($values, 512, JSON_THROW_ON_ERROR);
62: default : return \serialize($values);
63: }
64: } catch (\Exception $e) { throw new TransformationFailedException("Failed to unserialize: ".$e->getMessage());
65: } catch (\TypeError $t) { throw new TransformationFailedException("Failed to unserialize: ".$t->getMessage());
66: }
67: }
68:
69: }
70: