Sfoglia il codice sorgente

adjusts implementation to make it compatible with PHP 5.5

Johannes M. Schmitt 11 anni fa
parent
commit
6573645526

+ 12 - 1
src/JMS/Serializer/JsonSerializationVisitor.php

@@ -26,7 +26,18 @@ class JsonSerializationVisitor extends GenericSerializationVisitor
 
     public function getResult()
     {
-        return @json_encode($this->getRoot(), $this->options);
+        $result = @json_encode($this->getRoot(), $this->options);
+
+        switch (json_last_error()) {
+            case JSON_ERROR_NONE:
+                return $result;
+
+            case JSON_ERROR_UTF8:
+                throw new \RuntimeException('Your data could not be encoded because it contains invalid UTF8 characters.');
+
+            default:
+                throw new \RuntimeException(sprintf('An error occurred while encoding your data (error code %d).', json_last_error()));
+        }
     }
 
     public function getOptions()

+ 13 - 3
tests/JMS/Serializer/Tests/Serializer/JsonSerializationTest.php

@@ -179,14 +179,24 @@ class JsonSerializationTest extends BaseSerializationTest
 
     /**
      * @group encoding
+     * @expectedException RuntimeException
+     * @expectedExceptionMessage Your data could not be encoded because it contains invalid UTF8 characters.
      */
-    public function testSerializeWithNonUtf8EncodingHasConsistentBehavior()
+    public function testSerializeWithNonUtf8EncodingWhenDisplayErrorsOff()
     {
         ini_set('display_errors', 1);
-        $this->assertEquals('{"foo":"bar","bar":null}', $this->serialize(array('foo' => 'bar', 'bar' => pack("H*" ,'c32e'))));
+        $this->serialize(array('foo' => 'bar', 'bar' => pack("H*" ,'c32e')));
+    }
 
+    /**
+     * @group encoding
+     * @expectedException RuntimeException
+     * @expectedExceptionMessage Your data could not be encoded because it contains invalid UTF8 characters.
+     */
+    public function testSerializeWithNonUtf8EncodingWhenDisplayErrorsOn()
+    {
         ini_set('display_errors', 0);
-        $this->assertEquals('{"foo":"bar","bar":null}', $this->serialize(array('foo' => 'bar', 'bar' => pack("H*" ,'c32e'))));
+        $this->serialize(array('foo' => 'bar', 'bar' => pack("H*" ,'c32e')));
     }
 
     public function testSerializeArrayWithEmptyObject()