Преглед на файлове

Provide discardUnknonwnFields API in php (#3976)

* Provide discardUnknownFields API in php implementation

* Provide discardUnknownFields API in php c extension.
Paul Yang преди 7 години
родител
ревизия
74e7decbbf

+ 9 - 0
php/ext/google/protobuf/encode_decode.c

@@ -1614,3 +1614,12 @@ PHP_METHOD(Message, mergeFromJsonString) {
     stackenv_uninit(&se);
   }
 }
+
+PHP_METHOD(Message, discardUnknownFields) {
+  MessageHeader* msg = UNBOX(MessageHeader, getThis());
+  stringsink* unknown = DEREF(message_data(msg), 0, stringsink*);
+  if (unknown != NULL) {
+    stringsink_uninit(unknown);
+    DEREF(message_data(msg), 0, stringsink*) = NULL;
+  }
+}

+ 1 - 0
php/ext/google/protobuf/message.c

@@ -42,6 +42,7 @@ static void hex_to_binary(const char* hex, char** binary, int* binary_len);
 
 static  zend_function_entry message_methods[] = {
   PHP_ME(Message, clear, NULL, ZEND_ACC_PUBLIC)
+  PHP_ME(Message, discardUnknownFields, NULL, ZEND_ACC_PUBLIC)
   PHP_ME(Message, serializeToString, NULL, ZEND_ACC_PUBLIC)
   PHP_ME(Message, mergeFromString, NULL, ZEND_ACC_PUBLIC)
   PHP_ME(Message, serializeToJsonString, NULL, ZEND_ACC_PUBLIC)

+ 1 - 0
php/ext/google/protobuf/protobuf.h

@@ -969,6 +969,7 @@ PHP_METHOD(Message, serializeToString);
 PHP_METHOD(Message, mergeFromString);
 PHP_METHOD(Message, serializeToJsonString);
 PHP_METHOD(Message, mergeFromJsonString);
+PHP_METHOD(Message, discardUnknownFields);
 
 // -----------------------------------------------------------------------------
 // Type check / conversion.

+ 9 - 0
php/src/Google/Protobuf/Internal/Message.php

@@ -576,6 +576,15 @@ class Message
         }
     }
 
+    /**
+     * Clear all unknown fields previously parsed.
+     * @return null.
+     */
+    public function discardUnknownFields()
+    {
+        $this->unknown = "";
+    }
+
     /**
      * Merges the contents of the specified message into current message.
      *

+ 7 - 0
php/tests/encode_decode_test.php

@@ -466,6 +466,13 @@ class EncodeDecodeTest extends TestBase
         $m->mergeFromString($from);
         $to = $m->serializeToString();
         $this->assertSame(bin2hex($from), bin2hex($to));
+
+        $m = new TestMessage();
+        $from = hex2bin('F80601');
+        $m->mergeFromString($from);
+        $m->discardUnknownFields();
+        $to = $m->serializeToString();
+        $this->assertSame("", bin2hex($to));
     }
 
     public function testJsonEncode()