Skip to content
This repository has been archived by the owner on Nov 11, 2020. It is now read-only.

Commit

Permalink
Use primary read preference when reading newly persisted GridFS files
Browse files Browse the repository at this point in the history
  • Loading branch information
alcaeus committed Apr 27, 2018
1 parent 684f2d3 commit d7dcc75
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions lib/Doctrine/MongoDB/GridFS.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
}
}
}

0 comments on commit d7dcc75

Please sign in to comment.