@@ -1284,6 +1284,11 @@ void phongo_zval_to_bson(zval *data, php_phongo_bson_flags_t flags, bson_t *bson
1284
1284
* properties, we'll need to filter them out later. */
1285
1285
bool ht_data_from_properties = false;
1286
1286
1287
+ /* If the object is an instance of MongoDB\BSON\Persistable, we will need to
1288
+ * inject the PHP class name as a BSON key and ignore any existing key in
1289
+ * the return value of bsonSerialize(). */
1290
+ bool skip_odm_field = false;
1291
+
1287
1292
ZVAL_UNDEF (& obj_data );
1288
1293
1289
1294
switch (Z_TYPE_P (data )) {
@@ -1338,11 +1343,12 @@ void phongo_zval_to_bson(zval *data, php_phongo_bson_flags_t flags, bson_t *bson
1338
1343
if (instanceof_function (Z_OBJCE_P (data ), php_phongo_persistable_ce TSRMLS_CC )) {
1339
1344
#if PHP_VERSION_ID >= 70000
1340
1345
bson_append_binary (bson , PHONGO_ODM_FIELD_NAME , -1 , 0x80 , (const uint8_t * )Z_OBJCE_P (data )-> name -> val , Z_OBJCE_P (data )-> name -> len );
1341
- zend_hash_str_del (ht_data , PHONGO_ODM_FIELD_NAME , sizeof (PHONGO_ODM_FIELD_NAME )- 1 );
1342
1346
#else
1343
1347
bson_append_binary (bson , PHONGO_ODM_FIELD_NAME , -1 , 0x80 , (const uint8_t * )Z_OBJCE_P (data )-> name , strlen (Z_OBJCE_P (data )-> name ));
1344
- zend_hash_del (ht_data , PHONGO_ODM_FIELD_NAME , sizeof (PHONGO_ODM_FIELD_NAME ));
1345
1348
#endif
1349
+ /* Ensure that we ignore an existing key with the same name
1350
+ * if one exists in the bsonSerialize() return value. */
1351
+ skip_odm_field = true;
1346
1352
}
1347
1353
1348
1354
break ;
@@ -1387,6 +1393,10 @@ void phongo_zval_to_bson(zval *data, php_phongo_bson_flags_t flags, bson_t *bson
1387
1393
goto cleanup ;
1388
1394
}
1389
1395
1396
+ if (skip_odm_field && !strcmp (ZSTR_VAL (string_key ), PHONGO_ODM_FIELD_NAME )) {
1397
+ continue ;
1398
+ }
1399
+
1390
1400
if (flags & PHONGO_BSON_ADD_ID ) {
1391
1401
if (!strcmp (ZSTR_VAL (string_key ), "_id" )) {
1392
1402
flags &= ~PHONGO_BSON_ADD_ID ;
@@ -1439,6 +1449,10 @@ void phongo_zval_to_bson(zval *data, php_phongo_bson_flags_t flags, bson_t *bson
1439
1449
goto cleanup ;
1440
1450
}
1441
1451
1452
+ if (skip_odm_field && !strcmp (string_key , PHONGO_ODM_FIELD_NAME )) {
1453
+ continue ;
1454
+ }
1455
+
1442
1456
if (flags & PHONGO_BSON_ADD_ID ) {
1443
1457
if (!strcmp (string_key , "_id" )) {
1444
1458
flags &= ~PHONGO_BSON_ADD_ID ;
0 commit comments