Skip to content

Commit b4c1ada

Browse files
committed
Allow object or array from findOneAndUpdate
1 parent ba57f71 commit b4c1ada

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

src/Queue.php

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -186,10 +186,8 @@ public function get(array $query, $runningResetDuration, $waitDurationInMillis =
186186
$resetTimestamp = min(max(0, $resetTimestamp * 1000), self::MONGO_INT32_MAX);
187187

188188
$update = ['$set' => ['resetTimestamp' => new \MongoDB\BSON\UTCDateTime($resetTimestamp), 'running' => true]];
189-
$options = [
190-
'sort' => ['priority' => 1, 'created' => 1],
191-
'typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array'],
192-
];
189+
$findOneAndUpdateOptions = ['sort' => ['priority' => 1, 'created' => 1]];
190+
$findOneOptions = ['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']],
193191

194192
//ints overflow to floats, should be fine
195193
$end = microtime(true) + ($waitDurationInMillis / 1000.0);
@@ -203,14 +201,14 @@ public function get(array $query, $runningResetDuration, $waitDurationInMillis =
203201
} //@codeCoverageIgnoreEnd
204202

205203
while (true) {
206-
$message = $this->collection->findOneAndUpdate($completeQuery, $update, $options);
207-
//checking if _id exist because findAndModify doesnt seem to return null when it can't match the query on
208-
//older mongo extension
209-
if ($message !== null && array_key_exists('_id', $message)) {
204+
$id = $this->getIdFromMessage(
205+
$this->collection->findOneAndUpdate($completeQuery, $update, $findOneAndUpdateOptions)
206+
);
207+
if ($id !== null) {
210208
// findOneAndUpdate does not correctly return result according to typeMap options so just refetch.
211-
$message = $this->collection->findOne(['_id' => $message['_id']]);
209+
$message = $this->collection->findOne(['_id' => $id], $findOneOptions);
212210
//id on left of union operator so a possible id in payload doesnt wipe it out the generated one
213-
return ['id' => $message['_id']] + (array)$message['payload'];
211+
return ['id' => $id] + $message['payload'];
214212
}
215213

216214
if (microtime(true) >= $end) {
@@ -225,6 +223,19 @@ public function get(array $query, $runningResetDuration, $waitDurationInMillis =
225223
}
226224
//@codeCoverageIgnoreEnd
227225

226+
private function getIdFromMessage($message)
227+
{
228+
if (is_array($message)) {
229+
return array_key_exists('_id', $message) ? $message['_id'] : null;
230+
}
231+
232+
if (is_object($message)) {
233+
return isset($message->_id) ? $message->_id : null;
234+
}
235+
236+
return null;
237+
}
238+
228239
/**
229240
* Count queue messages.
230241
*

0 commit comments

Comments
 (0)