| 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: | |
| 9: | |
| 10: | |
| 11: | |
| 12: | class SerializedTransformer implements DataTransformerInterface |
| 13: | { |
| 14: | protected $type = "serialize"; |
| 15: | |
| 16: | |
| 17: | |
| 18: | |
| 19: | |
| 20: | |
| 21: | public function __construct(string $type = null) |
| 22: | { |
| 23: | if ($type !== null) $this->type = $type; |
| 24: | } |
| 25: | |
| 26: | |
| 27: | |
| 28: | |
| 29: | |
| 30: | |
| 31: | |
| 32: | |
| 33: | public function transform(mixed $values = null): mixed |
| 34: | { |
| 35: | if ($values === null) return null; |
| 36: | |
| 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: | |
| 51: | |
| 52: | |
| 53: | |
| 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: | |