Browse Source

Added the form error handler.

Deni 13 years ago
parent
commit
e2b47a81ce

+ 1 - 0
DependencyInjection/Configuration.php

@@ -57,6 +57,7 @@ class Configuration implements ConfigurationInterface
                                 ->end()
                             ->end()
                             ->booleanNode('array_collection')->defaultTrue()->end()
+                            ->booleanNode('form_error')->defaultTrue()->end()
                         ->end()
                     ->end()
                     ->arrayNode('metadata')

+ 5 - 0
DependencyInjection/JMSSerializerExtension.php

@@ -60,6 +60,11 @@ class JMSSerializerExtension extends Extension
             $container->removeDefinition('jms_serializer.array_collection_handler');
         }
 
+        // form error handler
+        if (!$config['handlers']['form_error']) {
+            $container->removeDefinition('jms_serializer.form_error_handler');
+        }
+
         // metadata
         if ('none' === $config['metadata']['cache']) {
             $container->removeAlias('jms_serializer.metadata.cache');

+ 5 - 0
Resources/config/services.xml

@@ -32,6 +32,7 @@
         
         <parameter key="jms_serializer.datetime_handler.class">JMS\SerializerBundle\Serializer\Handler\DateTimeHandler</parameter>
         <parameter key="jms_serializer.array_collection_handler.class">JMS\SerializerBundle\Serializer\Handler\ArrayCollectionHandler</parameter>
+        <parameter key="jms_serializer.form_error_handler.class">JMS\SerializerBundle\Serializer\Handler\FormErrorHandler</parameter>
     </parameters>
 
     <services>
@@ -140,5 +141,9 @@
         <service id="jms_serializer.array_collection_handler" class="%jms_serializer.array_collection_handler.class%" public="false">
             <tag name="jms_serializer.deserialization_handler" />
         </service>
+        <service id="jms_serializer.form_error_handler" class="%jms_serializer.form_error_handler.class%" public="false">
+            <argument type="service" id="translator" />
+            <tag name="jms_serializer.serialization_handler" />
+        </service>
     </services>
 </container>

+ 55 - 0
Serializer/Handler/FormErrorHandler.php

@@ -0,0 +1,55 @@
+<?php
+
+/*
+ * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+namespace JMS\SerializerBundle\Serializer\Handler;
+
+use Symfony\Component\Form\FormError;
+use Symfony\Component\Translation\TranslatorInterface;
+use JMS\SerializerBundle\Serializer\Handler\SerializationHandlerInterface;
+use JMS\SerializerBundle\Serializer\VisitorInterface;
+use JMS\SerializerBundle\Serializer\XmlSerializationVisitor;
+
+class FormErrorHandler implements SerializationHandlerInterface
+{
+    private $translator;
+
+    public function __construct(TranslatorInterface $translator)
+    {
+        $this->translator = $translator;
+    }
+
+    public function serialize(VisitorInterface $visitor, $data, $type, &$handled)
+    {
+        if (!$data instanceof FormError) {
+            return;
+        }
+
+        $handled = true;
+        $message = $this->translator->trans($data->getMessageTemplate(), $data->getMessageParameters(), 'validators');
+
+        if ($visitor instanceof XmlSerializationVisitor) {
+            if (null === $visitor->document) {
+                $visitor->document = $visitor->createDocument(null, null, true);
+            }
+
+            return $visitor->document->createCDATASection($message);
+        }
+
+        return $message;
+    }
+}

+ 23 - 5
Tests/Serializer/BaseSerializationTest.php

@@ -19,7 +19,7 @@
 namespace JMS\SerializerBundle\Tests\Serializer;
 
 use Doctrine\Common\Collections\ArrayCollection;
-
+use Symfony\Component\Form\FormError;
 use JMS\SerializerBundle\Serializer\Handler\DeserializationHandlerInterface;
 use JMS\SerializerBundle\Tests\Fixtures\AuthorList;
 use JMS\SerializerBundle\Serializer\VisitorInterface;
@@ -29,6 +29,7 @@ use JMS\SerializerBundle\Serializer\Construction\UnserializeObjectConstructor;
 use JMS\SerializerBundle\Serializer\JsonDeserializationVisitor;
 use JMS\SerializerBundle\Tests\Fixtures\Log;
 use JMS\SerializerBundle\Serializer\Handler\DateTimeHandler;
+use JMS\SerializerBundle\Serializer\Handler\FormErrorHandler;
 use JMS\SerializerBundle\Tests\Fixtures\Comment;
 use JMS\SerializerBundle\Tests\Fixtures\Author;
 use JMS\SerializerBundle\Tests\Fixtures\BlogPost;
@@ -188,6 +189,16 @@ abstract class BaseSerializationTest extends \PHPUnit_Framework_TestCase
         $this->assertEquals($object, $deserialized);
     }
 
+    public function testFormErrors()
+    {
+        $errors = array(
+            new FormError('This is the form error'),
+            new FormError('Another error')
+        );
+
+        $this->assertEquals($this->getContent('form_errors'), $this->serialize($errors));
+    }
+
     abstract protected function getContent($key);
     abstract protected function getFormat();
 
@@ -203,13 +214,13 @@ abstract class BaseSerializationTest extends \PHPUnit_Framework_TestCase
 
     protected function getSerializer()
     {
-        $customSerializationHandlers = $this->getSerializationHandlers();
-        $customDeserializationHandlers = $this->getDeserializationHandlers();
-
         $factory = new MetadataFactory(new AnnotationDriver(new AnnotationReader()));
         $namingStrategy = new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy());
         $objectConstructor = new UnserializeObjectConstructor();
 
+        $customSerializationHandlers = $this->getSerializationHandlers();
+        $customDeserializationHandlers = $this->getDeserializationHandlers();
+
         $serializationVisitors = array(
             'json' => new JsonSerializationVisitor($namingStrategy, $customSerializationHandlers),
             'xml'  => new XmlSerializationVisitor($namingStrategy, $customSerializationHandlers),
@@ -224,8 +235,15 @@ abstract class BaseSerializationTest extends \PHPUnit_Framework_TestCase
 
     protected function getSerializationHandlers()
     {
+        $translatorMock = $this->getMock('Symfony\\Component\\Translation\\TranslatorInterface');
+        $translatorMock
+            ->expects($this->any())
+            ->method('trans')
+            ->will($this->returnArgument(0));
+
         $handlers = array(
-            new DateTimeHandler()
+            new DateTimeHandler(),
+            new FormErrorHandler($translatorMock),
         );
 
         return $handlers;

+ 1 - 0
Tests/Serializer/JsonSerializationTest.php

@@ -45,6 +45,7 @@ class JsonSerializationTest extends BaseSerializationTest
             $outputs['blog_post'] = '{"title":"This is a nice title.","created_at":"2011-07-30T00:00:00+0000","is_published":false,"comments":[{"author":{"full_name":"Foo Bar"},"text":"foo"}],"author":{"full_name":"Foo Bar"}}';
             $outputs['log'] = '{"author_list":[{"full_name":"Johannes Schmitt"},{"full_name":"John Doe"}],"comments":[{"author":{"full_name":"Foo Bar"},"text":"foo"},{"author":{"full_name":"Foo Bar"},"text":"bar"},{"author":{"full_name":"Foo Bar"},"text":"baz"}]}';
             $outputs['lifecycle_callbacks'] = '{"name":"Foo Bar"}';
+            $outputs['form_errors'] = '["This is the form error","Another error"]';
         }
 
         if (!isset($outputs[$key])) {

+ 5 - 0
Tests/Serializer/xml/form_errors.xml

@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<result>
+  <entry><![CDATA[This is the form error]]></entry>
+  <entry><![CDATA[Another error]]></entry>
+</result>