ObjectBasedCustomHandler.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 (!in_array('JMS\SerializerBundle\Serializer\Handler\DeserializationHandlerInterface', class_implements($type))) {
  25. return;
  26. }
  27. $metadata = $this->metadataFactory->getMetadataForClass($type);
  28. $visitor->startVisitingObject($metadata, $data, $type);
  29. $instance = $visitor->getResult();
  30. $instance->deserialize($visitor, $data, $type, $handled);
  31. return $instance;
  32. }
  33. }