Skip to content

Commit 7c272a9

Browse files
committed
Add Model::findBy method
1 parent 650739e commit 7c272a9

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/Model.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
*/
1010
namespace Framework\MVC;
1111

12+
use Closure;
1213
use DateTime;
1314
use DateTimeZone;
1415
use Exception;
@@ -482,6 +483,28 @@ public function getPager() : Pager
482483
return $this->pager;
483484
}
484485

486+
/**
487+
* Find a row by column name and value.
488+
*
489+
* @param string $column
490+
* @param Closure|float|int|string|null $value
491+
*
492+
* @return array<string,float|int|string|null>|Entity|stdClass|null
493+
*/
494+
public function findBy(
495+
string $column,
496+
Closure | float | int | string | null $value
497+
) : array | Entity | stdClass | null {
498+
$data = $this->getDatabaseToRead()
499+
->select()
500+
->from($this->getTable())
501+
->whereEqual($column, $value)
502+
->limit(1)
503+
->run()
504+
->fetchArray();
505+
return $data ? $this->makeEntity($data) : null;
506+
}
507+
485508
/**
486509
* Find a row based on Primary Key.
487510
*

tests/ModelTest.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@ protected function setUp() : void
2727
$this->model = new ModelMock();
2828
}
2929

30+
public function testFindBy() : void
31+
{
32+
self::assertIsObject($this->model->findBy('id', 1));
33+
self::assertNull($this->model->findBy('id', 1000));
34+
self::assertIsObject($this->model->findBy('data', 'foo'));
35+
}
36+
3037
public function testFind() : void
3138
{
3239
self::assertIsObject($this->model->find(1));

0 commit comments

Comments
 (0)