HandlerRegistry.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace JMS\SerializerBundle\Serializer\Handler;
  3. use JMS\SerializerBundle\Serializer\GraphNavigator;
  4. class HandlerRegistry implements HandlerRegistryInterface
  5. {
  6. protected $handlers;
  7. public static function getDefaultMethod($direction, $type, $format)
  8. {
  9. if (false !== $pos = strrpos($type, '\\')) {
  10. $type = substr($type, $pos + 1);
  11. }
  12. switch ($direction) {
  13. case GraphNavigator::DIRECTION_DESERIALIZATION:
  14. return 'deserialize'.$type.'From'.$format;
  15. case GraphNavigator::DIRECTION_SERIALIZATION:
  16. return 'serialize'.$type.'To'.$format;
  17. default:
  18. throw new \LogicException(sprintf('The direction %s does not exist.', json_encode($direction)));
  19. }
  20. }
  21. public function __construct(array $handlers = array())
  22. {
  23. $this->handlers = $handlers;
  24. }
  25. public function registerSubscribingHandler(SubscribingHandlerInterface $handler)
  26. {
  27. foreach ($handler->getSubscribingMethods() as $methodData) {
  28. if ( ! isset($methodData['type'], $methodData['format'])) {
  29. throw new \RuntimeException(sprintf('For each subscribing method a "type" and "format" attribute must be given, but only got "%s" for %s.', implode('" and "', array_keys($methodData)), get_class($handler)));
  30. }
  31. $directions = array(GraphNavigator::DIRECTION_DESERIALIZATION, GraphNavigator::DIRECTION_SERIALIZATION);
  32. if (isset($methodData['direction'])) {
  33. $directions = array($methodData['direction']);
  34. }
  35. foreach ($directions as $direction) {
  36. $method = isset($methodData['method']) ? $methodData['method'] : self::getDefaultMethod($direction, $methodData['type'], $methodData['format']);
  37. $this->registerHandler($direction, $methodData['type'], $methodData['format'], array($handler, $method));
  38. }
  39. }
  40. }
  41. public function registerHandler($direction, $typeName, $format, $handler)
  42. {
  43. $this->handlers[$direction][$typeName][$format] = $handler;
  44. }
  45. public function getHandler($direction, $typeName, $format)
  46. {
  47. if ( ! isset($this->handlers[$direction][$typeName][$format])) {
  48. return null;
  49. }
  50. return $this->handlers[$direction][$typeName][$format];
  51. }
  52. }