Skip to content

Commit

Permalink
Merge pull request #221 from leroy-merlin-br/feat/add-refresh-method
Browse files Browse the repository at this point in the history
feat: add refresh method
  • Loading branch information
gabrielgomes94 authored Oct 18, 2023
2 parents cd3cbce + 012fe23 commit bb693a3
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Model/AbstractModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
16 changes: 16 additions & 0 deletions tests/Integration/PersistedDataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
20 changes: 20 additions & 0 deletions tests/Unit/Model/AbstractModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
}
}

0 comments on commit bb693a3

Please sign in to comment.