Source of file SerializedTransformer.php
Size: 2,476 Bytes - Last Modified: 2023-11-16T22:56:02+01:00
/home/websites/teicee/packagist/site/phpdoc/conf/../vendor/teicee/core-bundle/src/Form/DataTransformer/SerializedTransformer.php
| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 | <?phpnamespace TIC\CoreBundle\Form\DataTransformer; use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; /** * Transforms between a serialized data (string) and a data structure (mixed). * * Example: store a complex data (form compound) into a simple database column (varchar) */class SerializedTransformer implements DataTransformerInterface {protected $type = "serialize"; /** json | serialize (default) */ /** * Construct the data transformer with parameters (type of serialization). * * @param string $type Type of serialization method: json | serialize (default) */public function __construct(string $type = null) { if ($type !== null) $this->type = $type; } /** * Transforms a serialization string into a data structure. * * @param string $values Data serialized (all values into one string) * @return mixed Data structure (array, object, scalar...) * @throws TransformationFailedException If the given value is not a serialization. */public function transform(mixed $values = null): mixed { if ($values === null) return null; # if (! \is_string($values)) return $values;if (! \is_string($values)) throw new TransformationFailedException("Expected a string."); try { switch ($this->type) { case 'json' : return \json_decode($values, true, 512, JSON_THROW_ON_ERROR); default : return \unserialize($values); } } catch (\Exception $e) { throw new TransformationFailedException("Failed to unserialize: ".$e->getMessage()); } catch (\TypeError $t) { throw new TransformationFailedException("Failed to unserialize: ".$t->getMessage()); } } /** * Transforms a data structure into a serialization string. * * @param mixed $values Data structure (array, object, scalar...) * @return string Data serialized (all values into one string) */public function reverseTransform(mixed $values = null): ?string { if ($values === null) return null; try { switch ($this->type) { case 'json' : return \json_encode($values, 512, JSON_THROW_ON_ERROR); default : return \serialize($values); } } catch (\Exception $e) { throw new TransformationFailedException("Failed to unserialize: ".$e->getMessage()); } catch (\TypeError $t) { throw new TransformationFailedException("Failed to unserialize: ".$t->getMessage()); } } } |