Skip to content

Commit

Permalink
added findOrFail() method that throws an exception when a model could…
Browse files Browse the repository at this point in the history
… not be found
  • Loading branch information
Jared King committed Dec 29, 2015
1 parent dc432fe commit 6e71dca
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Infuse\ErrorStack;
use InvalidArgumentException;
use Pulsar\Driver\DriverInterface;
use Pulsar\Exception\NotFoundException;
use Pulsar\Relation\HasOne;
use Pulsar\Relation\BelongsTo;
use Pulsar\Relation\HasMany;
Expand Down Expand Up @@ -966,6 +967,25 @@ public static function find($id)
return $model->refreshWith($values);
}

/**
* Finds a single instance of a model given it's ID or throws an exception.
*
* @param mixed $id
*
* @return Model|false
*
* @throws ModelNotFoundException when a model could not be found
*/
public static function findOrFail($id)
{
$model = static::find($id);
if (!$model) {
throw new NotFoundException('Could not find the requested '.static::modelName());
}

return $model;
}

/**
* Gets the toal number of records matching an optional criteria.
*
Expand Down
31 changes: 31 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1002,6 +1002,37 @@ public function testFindFail()
$this->assertFalse(TestModel::find(101));
}

public function testFindOrFail()
{
$driver = Mockery::mock('Pulsar\Driver\DriverInterface');

$driver->shouldReceive('loadModel')
->andReturn(['id' => 100, 'answer' => 42])
->once();

TestModel::setDriver($driver);

$model = TestModel::findOrFail(100);
$this->assertInstanceOf('TestModel', $model);
$this->assertEquals(100, $model->id());
$this->assertEquals(42, $model->answer);
}

public function testFindOrFailNotFound()
{
$this->setExpectedException('Pulsar\Exception\NotFoundException');

$driver = Mockery::mock('Pulsar\Driver\DriverInterface');

$driver->shouldReceive('loadModel')
->andReturn(false)
->once();

TestModel::setDriver($driver);

$this->assertFalse(TestModel::findOrFail(101));
}

public function testTotalRecords()
{
$query = TestModel2::query();
Expand Down

0 comments on commit 6e71dca

Please sign in to comment.