ObjectBasedCustomHandler.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /*
  3. * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace JMS\SerializerBundle\Serializer\Handler;
  18. use Metadata\MetadataFactoryInterface;
  19. use JMS\SerializerBundle\Serializer\VisitorInterface;
  20. use JMS\SerializerBundle\Serializer\Construction\ObjectConstructorInterface;
  21. class ObjectBasedCustomHandler implements SerializationHandlerInterface, DeserializationHandlerInterface
  22. {
  23. private $objectConstructor;
  24. private $metadataFactory;
  25. public function __construct(ObjectConstructorInterface $objectConstructor, MetadataFactoryInterface $metadataFactory)
  26. {
  27. $this->objectConstructor = $objectConstructor;
  28. $this->metadataFactory = $metadataFactory;
  29. }
  30. public function serialize(VisitorInterface $visitor, $data, $type, &$handled)
  31. {
  32. if (!$data instanceof SerializationHandlerInterface) {
  33. return;
  34. }
  35. return $data->serialize($visitor, $data, $type, $handled);
  36. }
  37. public function deserialize(VisitorInterface $visitor, $data, $type, &$handled)
  38. {
  39. if (!class_exists($type)
  40. || !in_array('JMS\SerializerBundle\Serializer\Handler\DeserializationHandlerInterface', class_implements($type))
  41. ) {
  42. return;
  43. }
  44. $metadata = $this->metadataFactory->getMetadataForClass($type);
  45. $visitor->startVisitingObject($metadata, $data, $type);
  46. $instance = $visitor->getResult();
  47. $instance->deserialize($visitor, $data, $type, $handled);
  48. return $instance;
  49. }
  50. }