pdo-document/src/DocumentList.php

56 lines
1.7 KiB
PHP

<?php declare(strict_types=1);
namespace BitBadger\PDODocument;
use BitBadger\PDODocument\Mapper\Mapper;
use Generator;
use PDO;
use PDOStatement;
/**
* A lazy iterator of results in a list; implementations will create new connections to the database and close/dispose
* them as required once the results have been exhausted.
*
* @template TDoc The domain class for items returned by this list
*/
class DocumentList
{
/**
* Constructor
*
* @param PDO|null $pdo The database connection against which the query was opened
* @param PDOStatement|null $result The result of the query
* @param Mapper<TDoc> $mapper The mapper to deserialize JSON
*/
private function __construct(private ?PDO $pdo, private ?PDOStatement $result, private Mapper $mapper) { }
/**
* Construct a new document list
*
* @param string $query The query to run to retrieve results
* @param array $parameters An associative array of parameters for the query
* @param Mapper<TDoc> $mapper A mapper to deserialize JSON documents
* @return static The document list instance
* @throws DocumentException If any is encountered
*/
public static function create(string $query, array $parameters, Mapper $mapper): static
{
$pdo = Configuration::dbConn();
return new static($pdo, Custom::runQuery($query, $parameters, $pdo), $mapper);
}
/**
* The items from the query result
*
* @return Generator<TDoc> The items from the document list
*/
public function items(): Generator
{
if ($this->result) {
while ($row = $this->result->fetch(PDO::FETCH_ASSOC)) yield $this->mapper->map($row);
}
$this->result = null;
$this->pdo = null;
}
}