Skip to content

Commit

Permalink
Merge pull request #24 from Icinga/support-for-custom-result-sets
Browse files Browse the repository at this point in the history
Add support for custom result sets
  • Loading branch information
nilmerg committed Oct 8, 2021
2 parents 84c2b3b + 51507e4 commit d83ec78
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
43 changes: 42 additions & 1 deletion src/Query.php
Expand Up @@ -18,6 +18,7 @@
use ipl\Stdlib\Filter;
use ipl\Stdlib\Filters;
use IteratorAggregate;
use RuntimeException;
use SplObjectStorage;

/**
Expand All @@ -35,6 +36,9 @@ class Query implements Filterable, LimitOffsetInterface, OrderByInterface, Pagin
/** @var Connection Database connection */
protected $db;

/** @var string Class to return results as */
protected $resultSetClass = ResultSet::class;

/** @var Model Model to query */
protected $model;

Expand Down Expand Up @@ -80,6 +84,34 @@ public function setDb(Connection $db)
return $this;
}

/**
* Get the class to return results as
*
* @return string
*/
public function getResultSetClass()
{
return $this->resultSetClass;
}

/**
* Set the class to return results as
*
* @param string $class
*
* @return $this
*/
public function setResultSetClass($class)
{
if (! is_string($class)) {
throw new InvalidArgumentException('Argument $class must be a string');
}

$this->resultSetClass = $class;

return $this;
}

/**
* Get the model to query
*
Expand Down Expand Up @@ -598,7 +630,16 @@ public function dump()
*/
public function execute()
{
return new ResultSet($this->yieldResults(), $this->getLimit());
$class = $this->getResultSetClass();

$result = new $class($this->yieldResults(), $this->getLimit());
if (! $result instanceof ResultSet) {
throw new RuntimeException(
$class . ' must be an instance of ' . ResultSet::class
);
}

return $result;
}

/**
Expand Down
6 changes: 6 additions & 0 deletions tests/QueryTest.php
Expand Up @@ -23,6 +23,12 @@ public function testGetModelReturnsCorrectModelIfSet()
$this->assertSame($model, $query->getModel());
}

public function testExecuteReturnsCustomResultSet()
{
$query = (new Query())->setResultSetClass(TestResultSet::class);
$this->assertInstanceOf(TestResultSet::class, $query->execute());
}

public function testGetDbReturnsNullIfUnset()
{
$query = new Query();
Expand Down

0 comments on commit d83ec78

Please sign in to comment.