From c4867811e26bc32798ba24dd701bc2c35d49b027 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 25 Sep 2018 17:29:15 +0200 Subject: [PATCH] BaseModel: Added findOrNew --- src/Models/BaseModel.php | 12 ++++++++++++ tests/Unit/Models/BaseModelTest.php | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/Models/BaseModel.php b/src/Models/BaseModel.php index d5ded428..2367f5b6 100644 --- a/src/Models/BaseModel.php +++ b/src/Models/BaseModel.php @@ -36,4 +36,16 @@ abstract class BaseModel extends Model { return static::query()->find($id, $columns); } + + /** + * Find a model by its attributes or create a new one + * + * @param mixed $id + * @param array $columns + * @return static|Model + */ + public static function findOrNew($id, $columns = ['*']) + { + return static::query()->findOrNew($id, $columns); + } } diff --git a/tests/Unit/Models/BaseModelTest.php b/tests/Unit/Models/BaseModelTest.php index 9af55fa1..963ea64a 100644 --- a/tests/Unit/Models/BaseModelTest.php +++ b/tests/Unit/Models/BaseModelTest.php @@ -43,4 +43,26 @@ class BaseModelTest extends TestCase $this->assertEquals($anotherModel, $newModel); } + + /** + * @covers \Engelsystem\Models\BaseModel::findOrNew + */ + public function testFindOrNew() + { + /** @var QueryBuilder|MockObject $queryBuilder */ + $queryBuilder = $this->createMock(QueryBuilder::class); + BaseModelImplementation::$queryBuilder = $queryBuilder; + + $anotherModel = new BaseModelImplementation(); + + $queryBuilder->expects($this->once()) + ->method('findOrNew') + ->with(31337, ['lorem', 'ipsum']) + ->willReturn($anotherModel); + + $model = new BaseModelImplementation(); + $newModel = $model->findOrNew(31337, ['lorem', 'ipsum']); + + $this->assertEquals($anotherModel, $newModel); + } }