public static function LockDocumentStubbornly($id, $lockFieldName, $options = [], $db = null)
{
$db = $db ? $db : static::getDb();
$options = array_replace_recursive(
[
'mySession' => false,
'transactionOptions' => [],
'modifyOptions' => [],
'sleep' => 1000000,
'try' => 0,
],
$options
);
$options['modifyOptions']['new'] = true;
$session = $options['mySession'] ? $options['mySession'] : $db->startSessionOnce();
if ($session->getInTransaction()) {
throw new Exception('You can\'t use stubborn lock feature because current connection is in a transaction.');
}
$tiredCounter = 0;
StartStubborn:
$session->transaction->start($options['transactionOptions']);
try {
$doc = static::find()
->where(['_id' => $id])
->modify(
[
'$set' => [
$lockFieldName => new ObjectId
]
],
$options['modifyOptions'],
$db
);
return $doc;
} catch(\Exception $e) {
$session->transaction->rollBack();
$tiredCounter++;
if ($options['try'] !== 0 && $tiredCounter === $options['try']) {
throw $e;
}
usleep($options['sleep']);
goto StartStubborn;
}
}