diff --git a/src/LegacyRecord.php b/src/LegacyRecord.php index 5904e448..ff7e4d2f 100644 --- a/src/LegacyRecord.php +++ b/src/LegacyRecord.php @@ -399,4 +399,13 @@ public function bsonUnserialize(array $data): void $this->syncOriginalDocumentAttributes(); } + + /** + * Query model on database to retrieve an updated version of its attributes. + * @return self + */ + public function refresh(): self + { + return $this->first($this->_id); + } } diff --git a/tests/Integration/LegacyRecordTest.php b/tests/Integration/LegacyRecordTest.php index d2b0944f..8cb01e3b 100644 --- a/tests/Integration/LegacyRecordTest.php +++ b/tests/Integration/LegacyRecordTest.php @@ -55,4 +55,26 @@ public function testShouldOverrideSetAttributeMethods(): void $this->assertSame($expected, $entity->getAttributes()); } + + public function testRefreshModel(): void + { + // Set + $entity = new LegacyRecordUser(); + $entity->dynamic = true; + $entity->fill([ + 'name' => 'John Doe', + ]); + $entity->save(); + + // Actions + $entity->name = 'Jane Doe'; + $entity = $entity->refresh(); + + // Assertions + /** + * In this test, User must have his old name after refresh because its model wasn't persisted after setting its name to Jane Doe. + */ + $this->assertInstanceOf(LegacyRecordUser::class, $entity); + $this->assertSame('John Doe', $entity->name); + } } diff --git a/tests/Unit/LegacyRecordTest.php b/tests/Unit/LegacyRecordTest.php index d1f3e7ba..0a87a98f 100644 --- a/tests/Unit/LegacyRecordTest.php +++ b/tests/Unit/LegacyRecordTest.php @@ -437,4 +437,31 @@ public function testShouldGetSetWriteConcernInLegacyRecordClass(): void $this->entity->setWriteConcern(0); $this->assertEquals(0, $this->entity->getWriteConcern()); } + + public function testShouldRefreshModels(): void + { + // Set + $id = 'some-id-value'; + $entity = m::mock(LegacyRecord::class.'[getDataMapper]'); + $this->setProtected($entity, 'collection', 'mongolid'); + $entity->_id = $id; + $dataMapper = m::mock(); + Container::instance(get_class($entity), $entity); + + // Expectations + $entity->shouldReceive('getDataMapper') + ->andReturn($dataMapper); + + $dataMapper->shouldReceive('first') + ->once() + ->with('some-id-value', [], false) + ->andReturn($entity); + + // Actions + $result = $entity->refresh(); + + // Assertions + $this->assertSame($entity, $result); + } + }