Przeglądaj źródła

[Serializer] Added NormalizationAwareInterface

Jordi Boggiano 14 lat temu
rodzic
commit
24dcfef33f

+ 26 - 0
src/Symfony/Component/Serializer/Encoder/NormalizationAwareInterface.php

@@ -0,0 +1,26 @@
+<?php
+
+namespace Symfony\Component\Serializer\Encoder;
+
+use Symfony\Component\Serializer\SerializerInterface;
+
+/*
+ * This file is part of the Symfony framework.
+ *
+ * (c) Fabien Potencier <fabien@symfony.com>
+ *
+ * This source file is subject to the MIT license that is bundled
+ * with this source code in the file LICENSE.
+ */
+
+/**
+ * Defines the interface of encoders that will normalize data themselves
+ *
+ * Implementing this interface essentially just tells the Serializer that the
+ * data should not be pre-normalized before being passed to this Encoder.
+ *
+ * @author Jordi Boggiano <j.boggiano@seld.be>
+ */
+interface NormalizationAwareInterface
+{
+}

+ 1 - 1
src/Symfony/Component/Serializer/Encoder/XmlEncoder.php

@@ -20,7 +20,7 @@ use Symfony\Component\Serializer\SerializerInterface;
  * @author John Wards <jwards@whiteoctober.co.uk>
  * @author Fabian Vogler <fabian@equivalence.ch>
  */
-class XmlEncoder extends AbstractEncoder implements DecoderInterface
+class XmlEncoder extends AbstractEncoder implements DecoderInterface, NormalizationAwareInterface
 {
     private $dom;
     private $format;

+ 7 - 0
src/Symfony/Component/Serializer/Serializer.php

@@ -5,6 +5,7 @@ namespace Symfony\Component\Serializer;
 use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
 use Symfony\Component\Serializer\Encoder\EncoderInterface;
 use Symfony\Component\Serializer\Encoder\DecoderInterface;
+use Symfony\Component\Serializer\Encoder\NormalizationAwareInterface;
 
 /*
  * This file is part of the Symfony framework.
@@ -39,6 +40,12 @@ class Serializer implements SerializerInterface
      */
     public function serialize($data, $format)
     {
+        if (!$this->hasEncoder($format)) {
+            throw new \UnexpectedValueException('No encoder registered for the '.$format.' format');
+        }
+        if ($this->getEncoder($format) instanceof NormalizationAwareInterface) {
+            $data = $this->normalize($data);
+        }
         return $this->encode($data, $format);
     }