Serializer.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. <?php
  2. namespace Symfony\Component\Serializer;
  3. use Symfony\Component\Serializer\Encoder\EncoderInterface;
  4. use Symfony\Component\Serializer\Encoder\DecoderInterface;
  5. use Symfony\Component\Serializer\Encoder\NormalizationAwareInterface;
  6. use Symfony\Component\Serializer\Exception\RuntimeException;
  7. use Symfony\Component\Serializer\Exception\LogicException;
  8. use Symfony\Component\Serializer\Exception\UnexpectedValueException;
  9. /*
  10. * This file is part of the Symfony framework.
  11. *
  12. * (c) Fabien Potencier <fabien@symfony.com>
  13. *
  14. * This source file is subject to the MIT license that is bundled
  15. * with this source code in the file LICENSE.
  16. */
  17. /**
  18. * Serializer serializes and deserializes data
  19. *
  20. * objects are turned into arrays by normalizers
  21. * arrays are turned into various output formats by encoders
  22. *
  23. * $serializer->serialize($obj, 'xml')
  24. * $serializer->decode($data, 'xml')
  25. * $serializer->denormalize($data, 'Class', 'xml')
  26. *
  27. * @author Jordi Boggiano <j.boggiano@seld.be>
  28. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  29. * @author Lukas Kahwe Smith <smith@pooteeweet.org>
  30. */
  31. class Serializer implements SerializerInterface
  32. {
  33. protected $normalizers = array();
  34. protected $encoders = array();
  35. protected $normalizerCache = array();
  36. protected $denormalizerCache = array();
  37. public function __construct(array $normalizers = array(), array $encoders = array())
  38. {
  39. foreach ($normalizers as $normalizer) {
  40. if ($normalizer instanceof SerializerAwareInterface) {
  41. $normalizer->setSerializer($this);
  42. }
  43. }
  44. $this->normalizers = $normalizers;
  45. foreach ($encoders as $encoder) {
  46. if ($encoder instanceof SerializerAwareInterface) {
  47. $encoder->setSerializer($this);
  48. }
  49. }
  50. $this->encoders = $encoders;
  51. }
  52. /**
  53. * {@inheritdoc}
  54. */
  55. public final function serialize($data, $format)
  56. {
  57. if (!$this->supportsSerialization($format)) {
  58. throw new UnexpectedValueException('Serialization for the format '.$format.' is not supported');
  59. }
  60. $encoder = $this->getEncoder($format);
  61. if (!$encoder instanceof NormalizationAwareInterface) {
  62. $data = $this->normalize($data, $format);
  63. }
  64. return $this->encode($data, $format);
  65. }
  66. /**
  67. * {@inheritdoc}
  68. */
  69. public final function deserialize($data, $type, $format)
  70. {
  71. if (!$this->supportsDeserialization($format)) {
  72. throw new UnexpectedValueException('Deserialization for the format '.$format.' is not supported');
  73. }
  74. $data = $this->decode($data, $format);
  75. return $this->denormalize($data, $type, $format);
  76. }
  77. /**
  78. * {@inheritdoc}
  79. */
  80. public function normalize($data, $format = null)
  81. {
  82. if (null === $data || is_scalar($data)) {
  83. return $data;
  84. }
  85. if ($data instanceof \Traversable) {
  86. $normalized = array();
  87. foreach ($data as $key => $val) {
  88. $normalized[$key] = $this->normalize($val, $format);
  89. }
  90. return $normalized;
  91. }
  92. if (is_object($data)) {
  93. return $this->normalizeObject($data, $format);
  94. }
  95. if (is_array($data)) {
  96. foreach ($data as $key => $val) {
  97. $data[$key] = $this->normalize($val, $format);
  98. }
  99. return $data;
  100. }
  101. throw new UnexpectedValueException('An unexpected value could not be normalized: '.var_export($data, true));
  102. }
  103. /**
  104. * {@inheritdoc}
  105. */
  106. public function denormalize($data, $type, $format = null)
  107. {
  108. return $this->denormalizeObject($data, $type, $format);
  109. }
  110. /**
  111. * {@inheritdoc}
  112. */
  113. public final function encode($data, $format)
  114. {
  115. return $this->getEncoder($format)->encode($data, $format);
  116. }
  117. /**
  118. * {@inheritdoc}
  119. */
  120. public final function decode($data, $format)
  121. {
  122. return $this->getEncoder($format)->decode($data, $format);
  123. }
  124. /**
  125. * Normalizes an object into a set of arrays/scalars
  126. *
  127. * @param object $object object to normalize
  128. * @param string $format format name, present to give the option to normalizers to act differently based on formats
  129. * @return array|scalar
  130. */
  131. private function normalizeObject($object, $format = null)
  132. {
  133. if (!$this->normalizers) {
  134. throw new LogicException('You must register at least one normalizer to be able to normalize objects.');
  135. }
  136. $class = get_class($object);
  137. // If normalization is supported, cached normalizer will exist
  138. if ($this->supportsNormalization($object, $format)) {
  139. return $this->normalizerCache[$class][$format]->normalize($object, $format);
  140. }
  141. throw new UnexpectedValueException('Could not normalize object of type '.$class.', no supporting normalizer found.');
  142. }
  143. /**
  144. * Denormalizes data back into an object of the given class
  145. *
  146. * @param mixed $data data to restore
  147. * @param string $class the expected class to instantiate
  148. * @param string $format format name, present to give the option to normalizers to act differently based on formats
  149. * @return object
  150. */
  151. private function denormalizeObject($data, $class, $format = null)
  152. {
  153. if (!$this->normalizers) {
  154. throw new LogicException('You must register at least one normalizer to be able to denormalize objects.');
  155. }
  156. if (isset($this->denormalizerCache[$class][$format])) {
  157. return $this->denormalizerCache[$class][$format]->denormalize($data, $class, $format);
  158. }
  159. foreach ($this->normalizers as $normalizer) {
  160. if ($normalizer->supportsDenormalization($data, $class, $format)) {
  161. $this->denormalizerCache[$class][$format] = $normalizer;
  162. return $normalizer->denormalize($data, $class, $format);
  163. }
  164. }
  165. throw new UnexpectedValueException('Could not denormalize object of type '.$class.', no supporting normalizer found.');
  166. }
  167. /**
  168. * Check if normalizer cache or normalizers supports provided object, which will then be cached
  169. *
  170. * @param object $object Object to test for normalization support
  171. * @param string $format Format name, needed for normalizers to pivot on
  172. */
  173. protected function supportsNormalization($object, $format)
  174. {
  175. $class = get_class($object);
  176. if (isset($this->normalizerCache[$class][$format])) {
  177. return true;
  178. }
  179. foreach ($this->normalizers as $normalizer) {
  180. if ($normalizer->supportsNormalization($object, $format)) {
  181. $this->normalizerCache[$class][$format] = $normalizer;
  182. return true;
  183. }
  184. }
  185. return false;
  186. }
  187. /**
  188. * {@inheritdoc}
  189. */
  190. public function supportsSerialization($format)
  191. {
  192. return $this->supportsEncoding($format);
  193. }
  194. /**
  195. * {@inheritdoc}
  196. */
  197. public function supportsDeserialization($format)
  198. {
  199. return $this->supportsDecoding($format);
  200. }
  201. /**
  202. * {@inheritdoc}
  203. */
  204. public function supportsEncoding($format)
  205. {
  206. try {
  207. $encoder = $this->getEncoder($format);
  208. } catch (\RuntimeException $e) {
  209. return false;
  210. }
  211. return $encoder instanceof EncoderInterface;
  212. }
  213. /**
  214. * {@inheritdoc}
  215. */
  216. public function supportsDecoding($format)
  217. {
  218. try {
  219. $encoder = $this->getEncoder($format);
  220. } catch (\RuntimeException $e) {
  221. return false;
  222. }
  223. return $encoder instanceof DecoderInterface;
  224. }
  225. /**
  226. * {@inheritdoc}
  227. */
  228. public function getEncoder($format)
  229. {
  230. if (!isset($this->encoders[$format])) {
  231. throw new RuntimeException(sprintf('No encoder found for format "%s".', $format));
  232. }
  233. return $this->encoders[$format];
  234. }
  235. }