public function testUpdateModelPessimisticLock() { $lockCollection = $this->database->selectCollection('storage_lock_test'); $pessimisticLock = new PessimisticLock($lockCollection); $pessimisticLock->createIndexes(); $collection = $this->database->selectCollection('storage_test'); $hydrator = new Hydrator(Model::class); $storage = new MongodbStorage($collection, $hydrator, $pessimisticLock); $model = new Model(); $model->values = ['foo' => 'fooVal', 'bar' => 'barVal']; $result = $storage->insert($model); //guard $this->assertTrue($result->isAcknowledged()); $storage->lock($model->values['_id'], function ($lockedModel, $storage) use($model) { $this->assertInstanceOf(Model::class, $lockedModel); $this->assertEquals($model->values, $lockedModel->values); $this->assertInstanceOf(MongodbStorage::class, $storage); $model->values['ololo'] = 'ololoVal'; $result = $storage->update($model); //guard $this->assertTrue($result->isAcknowledged()); }); $foundModel = $storage->findOne(['_id' => new ObjectID($model->values['_id'])]); $this->assertInstanceOf(Model::class, $foundModel); $this->assertEquals($model->values, $foundModel->values); }
/** * @expectedException \RuntimeException * @expectedExceptionMessage Cannot obtain the lock for id "5669dd8f56c02c4628031635". Timeout after 2 seconds */ public function testWaitForLockIsNotReleased() { $lockCollection = $this->database->selectCollection('storage_lock_test'); $pessimisticLock = new PessimisticLock($lockCollection); $pessimisticLock->createIndexes(); $pessimisticLock->lock('5669dd8f56c02c4628031635'); $pessimisticLock->lock('5669dd8f56c02c4628031635', 2); }
/** * @param $id * @param callable $lockCallback */ public function lock($id, callable $lockCallback) { if (false == $this->pessimisticLock) { throw new \LogicException('Cannot lock. The PessimisticLock instance is not injected'); } $this->pessimisticLock->lock($id); try { if ($model = $this->findOne(['_id' => new ObjectID((string) $id)])) { call_user_func($lockCallback, $model, $this); } } finally { $this->pessimisticLock->unlock($id); } }