ObjectBasedCustomHandler.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 $constructor, MetadataFactoryInterface $metadata)
  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 (!is_a($type, 'JMS\SerializerBundle\Serializer\Handler\DeserializationHandlerInterface')) {
  25. return;
  26. }
  27. $metadata = $this->metadataFactory->getMetadataForClass($type);
  28. $instance = $this->objectConstructor->construct($visitor, $metadata, $data, $type);
  29. $instance->deserialize($visitor, $data, $type, $handled);
  30. return $instance;
  31. }
  32. }