66use MongoDB \Driver \Cursor ;
77use MongoDB \Driver \Manager ;
88use MongoDB \Driver \ReadPreference ;
9+ use MongoDB \Model \BSONDocument ;
910use InvalidArgumentException ;
1011use stdClass ;
1112use Traversable ;
@@ -42,8 +43,8 @@ protected function assertCommandSucceeded($document)
4243 protected function assertSameDocument ($ expectedDocument , $ actualDocument )
4344 {
4445 $ this ->assertEquals (
45- is_object ( $ expectedDocument ) ? ( array ) $ expectedDocument : $ expectedDocument ,
46- is_object ( $ actualDocument ) ? ( array ) $ actualDocument : $ actualDocument
46+ $ this -> normalizeBSON ( $ expectedDocument) ,
47+ $ this -> normalizeBSON ( $ actualDocument)
4748 );
4849 }
4950
@@ -58,7 +59,7 @@ protected function assertSameDocuments(array $expectedDocuments, $actualDocument
5859 }
5960
6061 $ normalizeRootDocuments = function ($ document ) {
61- return is_object ( $ document ) ? ( array ) $ document : $ document ;
62+ return $ this -> normalizeBSON ( $ document) ;
6263 };
6364
6465 $ this ->assertEquals (
@@ -85,4 +86,48 @@ protected function getServerVersion(ReadPreference $readPreference = null)
8586
8687 return $ document ['version ' ];
8788 }
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+ }
88133}
0 commit comments