diff --git a/lib/Doctrine/MongoDB/GridFS.php b/lib/Doctrine/MongoDB/GridFS.php index 26a5aad4..74f49994 100644 --- a/lib/Doctrine/MongoDB/GridFS.php +++ b/lib/Doctrine/MongoDB/GridFS.php @@ -74,10 +74,15 @@ public function storeFile($file, array &$document, array $options = []) } $document = array_merge(['_id' => $id], $document); - $gridFsFile = $this->mongoCollection->get($id); + $gridFsFile = $this->withPrimaryReadPreference(function () use ($id) { + return $this->mongoCollection->get($id); + }); + + if ( ! $gridFsFile instanceof \MongoGridFSFile) { + throw new \LogicException('Could not find newly persisted GridFS file'); + } - // TODO: Consider throwing exception if file cannot be fetched - $file->setMongoGridFSFile($this->mongoCollection->get($id)); + $file->setMongoGridFSFile($gridFsFile); return $file; } @@ -288,4 +293,24 @@ protected function doUpdate(array $query, array $newObj, array $options = []) $options = isset($options['safe']) ? $this->convertWriteConcern($options) : $options; return $this->mongoCollection->update($query, $newObj, $options); } + + /** + * Executes a closure with a temporary primary read preference. + * + * @param \Closure $closure + * + * @return mixed + */ + private function withPrimaryReadPreference(\Closure $closure) + { + $prevReadPref = $this->mongoCollection->getReadPreference(); + $this->mongoCollection->setReadPreference(\MongoClient::RP_PRIMARY); + + try { + return $closure(); + } finally { + $prevTags = ! empty($prevReadPref['tagsets']) ? $prevReadPref['tagsets'] : []; + $this->mongoCollection->setReadPreference($prevReadPref['type'], $prevTags); + } + } }