6
6
use MongoDB \Driver \Cursor ;
7
7
use MongoDB \Driver \Manager ;
8
8
use MongoDB \Driver \ReadPreference ;
9
+ use MongoDB \Model \BSONDocument ;
9
10
use InvalidArgumentException ;
10
11
use stdClass ;
11
12
use Traversable ;
@@ -42,8 +43,8 @@ protected function assertCommandSucceeded($document)
42
43
protected function assertSameDocument ($ expectedDocument , $ actualDocument )
43
44
{
44
45
$ this ->assertEquals (
45
- is_object ( $ expectedDocument ) ? ( array ) $ expectedDocument : $ expectedDocument ,
46
- is_object ( $ actualDocument ) ? ( array ) $ actualDocument : $ actualDocument
46
+ $ this -> normalizeBSON ( $ expectedDocument) ,
47
+ $ this -> normalizeBSON ( $ actualDocument)
47
48
);
48
49
}
49
50
@@ -58,7 +59,7 @@ protected function assertSameDocuments(array $expectedDocuments, $actualDocument
58
59
}
59
60
60
61
$ normalizeRootDocuments = function ($ document ) {
61
- return is_object ( $ document ) ? ( array ) $ document : $ document ;
62
+ return $ this -> normalizeBSON ( $ document) ;
62
63
};
63
64
64
65
$ this ->assertEquals (
@@ -85,4 +86,48 @@ protected function getServerVersion(ReadPreference $readPreference = null)
85
86
86
87
return $ document ['version ' ];
87
88
}
89
+
90
+ /**
91
+ * Normalizes a BSON document or array for use with assertEquals().
92
+ *
93
+ * The argument will be converted to a BSONArray or BSONDocument based on
94
+ * its type and keys. Document fields will be sorted alphabetically. Each
95
+ * value within the array or document will then be normalized recursively.
96
+ *
97
+ * @param array|object $bson
98
+ * @return BSONDocument|BSONArray
99
+ * @throws InvalidArgumentException if $bson is not an array or object
100
+ */
101
+ private function normalizeBSON ($ bson )
102
+ {
103
+ if ( ! is_array ($ bson ) && ! is_object ($ bson )) {
104
+ throw new InvalidArgumentException ('$bson is not an array or object ' );
105
+ }
106
+
107
+ if ($ bson instanceof BSONArray || (is_array ($ bson ) && $ bson === array_values ($ bson ))) {
108
+ if ( ! $ bson instanceof BSONArray) {
109
+ $ bson = new BSONArray ($ bson );
110
+ }
111
+ } else {
112
+ if ( ! $ bson instanceof BSONDocument) {
113
+ $ bson = new BSONDocument ((array ) $ bson );
114
+ }
115
+
116
+ $ bson ->ksort ();
117
+ }
118
+
119
+ foreach ($ bson as $ key => $ value ) {
120
+ if ($ value instanceof BSONArray || (is_array ($ value ) && $ value === array_values ($ value ))) {
121
+ $ bson [$ key ] = $ this ->normalizeBSON ($ value );
122
+ continue ;
123
+ }
124
+
125
+ if ($ value instanceof stdClass || $ value instanceof BSONDocument || is_array ($ value )) {
126
+ $ bson [$ key ] = $ this ->normalizeBSON ($ value );
127
+ continue ;
128
+ }
129
+ }
130
+
131
+ return $ bson ;
132
+ }
88
133
}
0 commit comments