ObjectBasedCustomHandler.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace JMS\SerializerBundle\Serializer\Handler;
  3. use Metadata\MetadataFactoryInterface;
  4. use JMS\SerializerBundle\Serializer\VisitorInterface;
  5. use JMS\SerializerBundle\Serializer\Construction\ObjectConstructorInterface;
  6. class ObjectBasedCustomHandler implements SerializationHandlerInterface, DeserializationHandlerInterface
  7. {
  8. private $objectConstructor;
  9. private $metadataFactory;
  10. public function __construct(ObjectConstructorInterface $objectConstructor, MetadataFactoryInterface $metadataFactory)
  11. {
  12. $this->objectConstructor = $objectConstructor;
  13. $this->metadataFactory = $metadataFactory;
  14. }
  15. public function serialize(VisitorInterface $visitor, $data, $type, &$handled)
  16. {
  17. if (!$data instanceof SerializationHandlerInterface) {
  18. return;
  19. }
  20. return $data->serialize($visitor, $data, $type, $handled);
  21. }
  22. public function deserialize(VisitorInterface $visitor, $data, $type, &$handled)
  23. {
  24. if (!class_exists($type)
  25. || !in_array('JMS\SerializerBundle\Serializer\Handler\DeserializationHandlerInterface', class_implements($type))
  26. ) {
  27. return;
  28. }
  29. $metadata = $this->metadataFactory->getMetadataForClass($type);
  30. $visitor->startVisitingObject($metadata, $data, $type);
  31. $instance = $visitor->getResult();
  32. $instance->deserialize($visitor, $data, $type, $handled);
  33. return $instance;
  34. }
  35. }