cursor = $cursor; } /** * Convert cursor to array with BSON types converted to native PHP types */ public function toArray(): array { $result = iterator_to_array($this->cursor); return $this->convertBsonToNative($result); } /** * Get iterator for foreach loops * Note: Items will be returned as-is (may contain BSON objects) * Use toArray() if you need full conversion */ public function getIterator(): Traversable { return $this->cursor; } /** * Get underlying MongoDB cursor */ public function getMongoCursor(): Iterator { return $this->cursor; } /** * Convert BSON objects to native PHP types * Handles ObjectId, UTCDateTime, and other BSON types */ private function convertBsonToNative(mixed $data): mixed { if (is_array($data)) { foreach ($data as $key => $value) { $data[$key] = $this->convertBsonToNative($value); } return $data; } if (is_object($data)) { // Convert MongoDB BSON ObjectId to string if ($data instanceof \MongoDB\BSON\ObjectId) { return (string) $data; } // Convert MongoDB BSON UTCDateTime to ISO8601 string if ($data instanceof \MongoDB\BSON\UTCDateTime) { return $data->toDateTime()->format('c'); } // Convert other objects to arrays recursively if (method_exists($data, 'bsonSerialize')) { return $this->convertBsonToNative($data->bsonSerialize()); } // Convert stdClass and other objects to array $array = (array) $data; return $this->convertBsonToNative($array); } return $data; } }