From 012fe233aa0717f9a4824b3cf33561c7a4a67360 Mon Sep 17 00:00:00 2001 From: Gabriel Date: Tue, 10 Oct 2023 15:52:45 -0300 Subject: [PATCH] feat: add refresh method --- src/Model/AbstractModel.php | 9 +++++++++ tests/Integration/PersistedDataTest.php | 16 ++++++++++++++++ tests/Unit/Model/AbstractModelTest.php | 20 ++++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/src/Model/AbstractModel.php b/src/Model/AbstractModel.php index 90aa79d1..32a76413 100644 --- a/src/Model/AbstractModel.php +++ b/src/Model/AbstractModel.php @@ -183,6 +183,15 @@ public function delete(): bool return $this->execute('delete'); } + /** + * Query model on database to retrieve an updated version of its attributes. + * @return self + */ + public function refresh(): self + { + return $this->first($this->_id); + } + /** * Dynamically retrieve attributes on the model. * diff --git a/tests/Integration/PersistedDataTest.php b/tests/Integration/PersistedDataTest.php index fba8ce92..2589cd34 100644 --- a/tests/Integration/PersistedDataTest.php +++ b/tests/Integration/PersistedDataTest.php @@ -134,6 +134,22 @@ public function testUpdateData(): void $this->assertEquals($expected, $result->toArray()); } + public function testRefreshModel(): void + { + // Set + $user = $this->getUser(true); + $user->name = 'Jane Doe'; + + // Actions + $result = $user->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->assertSame('John Doe', $result->name); + } + private function getUser(bool $save = false): ReferencedUser { $user = new ReferencedUser(); diff --git a/tests/Unit/Model/AbstractModelTest.php b/tests/Unit/Model/AbstractModelTest.php index 73e37e8c..e6ad1f17 100644 --- a/tests/Unit/Model/AbstractModelTest.php +++ b/tests/Unit/Model/AbstractModelTest.php @@ -2,6 +2,7 @@ namespace Mongolid\Model; use Mockery as m; +use MongoDB\BSON\ObjectId; use MongoDB\BSON\Persistable; use MongoDB\BSON\Serializable; use MongoDB\BSON\Type; @@ -588,4 +589,23 @@ public function setShortNameDocumentAttribute($value): string // Assertions $this->assertSame('MY AWESOME NAME', $result); } + + public function testShouldRefreshModels(): void + { + // Set + $builder = $this->instance(Builder::class, m::mock(Builder::class)); + $this->model->_id = 'some-id-value'; + + // Expectations + $builder + ->expects('first') + ->with(m::type(get_class($this->model)), 'some-id-value', [], false) + ->andReturn($this->model); + + // Actions + $result = $this->model->refresh(); + + // Assertions + $this->assertSame($this->model, $result); + } }