Skip to content

Commit

Permalink
Add Model::findBy method
Browse files Browse the repository at this point in the history
  • Loading branch information
natanfelles committed Jan 30, 2023
1 parent 650739e commit 7c272a9
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Model.php
Expand Up @@ -9,6 +9,7 @@
*/
namespace Framework\MVC;

use Closure;
use DateTime;
use DateTimeZone;
use Exception;
Expand Down Expand Up @@ -482,6 +483,28 @@ public function getPager() : Pager
return $this->pager;
}

/**
* Find a row by column name and value.
*
* @param string $column
* @param Closure|float|int|string|null $value
*
* @return array<string,float|int|string|null>|Entity|stdClass|null
*/
public function findBy(
string $column,
Closure | float | int | string | null $value
) : array | Entity | stdClass | null {
$data = $this->getDatabaseToRead()
->select()
->from($this->getTable())
->whereEqual($column, $value)
->limit(1)
->run()
->fetchArray();
return $data ? $this->makeEntity($data) : null;
}

/**
* Find a row based on Primary Key.
*
Expand Down
7 changes: 7 additions & 0 deletions tests/ModelTest.php
Expand Up @@ -27,6 +27,13 @@ protected function setUp() : void
$this->model = new ModelMock();
}

public function testFindBy() : void
{
self::assertIsObject($this->model->findBy('id', 1));
self::assertNull($this->model->findBy('id', 1000));
self::assertIsObject($this->model->findBy('data', 'foo'));
}

public function testFind() : void
{
self::assertIsObject($this->model->find(1));
Expand Down

0 comments on commit 7c272a9

Please sign in to comment.