@@ -401,6 +401,11 @@ void php_phongo_zval_to_bson(zval *data, php_phongo_bson_flags_t flags, bson_t *
401
401
* properties, we'll need to filter them out later. */
402
402
bool ht_data_from_properties = false;
403
403
404
+ /* If the object is an instance of MongoDB\BSON\Persistable, we will need to
405
+ * inject the PHP class name as a BSON key and ignore any existing key in
406
+ * the return value of bsonSerialize(). */
407
+ bool skip_odm_field = false;
408
+
404
409
ZVAL_UNDEF (& obj_data );
405
410
406
411
switch (Z_TYPE_P (data )) {
@@ -455,11 +460,12 @@ void php_phongo_zval_to_bson(zval *data, php_phongo_bson_flags_t flags, bson_t *
455
460
if (instanceof_function (Z_OBJCE_P (data ), php_phongo_persistable_ce TSRMLS_CC )) {
456
461
#if PHP_VERSION_ID >= 70000
457
462
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 );
458
- zend_hash_str_del (ht_data , PHONGO_ODM_FIELD_NAME , sizeof (PHONGO_ODM_FIELD_NAME )- 1 );
459
463
#else
460
464
bson_append_binary (bson , PHONGO_ODM_FIELD_NAME , -1 , 0x80 , (const uint8_t * )Z_OBJCE_P (data )-> name , strlen (Z_OBJCE_P (data )-> name ));
461
- zend_hash_del (ht_data , PHONGO_ODM_FIELD_NAME , sizeof (PHONGO_ODM_FIELD_NAME ));
462
465
#endif
466
+ /* Ensure that we ignore an existing key with the same name
467
+ * if one exists in the bsonSerialize() return value. */
468
+ skip_odm_field = true;
463
469
}
464
470
465
471
break ;
@@ -504,6 +510,10 @@ void php_phongo_zval_to_bson(zval *data, php_phongo_bson_flags_t flags, bson_t *
504
510
goto cleanup ;
505
511
}
506
512
513
+ if (skip_odm_field && !strcmp (ZSTR_VAL (string_key ), PHONGO_ODM_FIELD_NAME )) {
514
+ continue ;
515
+ }
516
+
507
517
if (flags & PHONGO_BSON_ADD_ID ) {
508
518
if (!strcmp (ZSTR_VAL (string_key ), "_id" )) {
509
519
flags &= ~PHONGO_BSON_ADD_ID ;
@@ -556,6 +566,10 @@ void php_phongo_zval_to_bson(zval *data, php_phongo_bson_flags_t flags, bson_t *
556
566
goto cleanup ;
557
567
}
558
568
569
+ if (skip_odm_field && !strcmp (string_key , PHONGO_ODM_FIELD_NAME )) {
570
+ continue ;
571
+ }
572
+
559
573
if (flags & PHONGO_BSON_ADD_ID ) {
560
574
if (!strcmp (string_key , "_id" )) {
561
575
flags &= ~PHONGO_BSON_ADD_ID ;
0 commit comments