Files
database/src/Implement/ResultSet.php

82 lines
1.7 KiB
PHP
Raw Normal View History

2022-09-08 20:02:05 -04:00
<?php
namespace Database\Implement;
2022-09-08 20:02:05 -04:00
use PDO;
use PDOStatement;
use Database\Define;
use Database\Exception\Database\BlankResult;
2022-09-08 20:02:05 -04:00
class ResultSet implements Define\Database\ResultSet
2022-09-08 20:02:05 -04:00
{
public function __construct(PDOStatement $statement)
{
$this->setStatement($statement);
}
protected PDOStatement $statement;
2023-02-28 23:41:51 -03:00
public function getStatement(): PDOStatement
2022-09-08 20:02:05 -04:00
{
2023-02-28 23:41:51 -03:00
return $this->statement;
2022-09-08 20:02:05 -04:00
}
protected function setStatement(PDOStatement $statement): self
2022-09-08 20:02:05 -04:00
{
2023-02-28 23:41:51 -03:00
$this->statement = $statement;
return $this;
2022-09-08 20:02:05 -04:00
}
public function execute(array $data): self
2022-09-08 20:02:05 -04:00
{
2023-02-28 23:41:51 -03:00
$this->statement->execute($data);
2022-09-08 20:02:05 -04:00
return $this;
}
/**
* @return PDOStatement
* @throws BlankResult
*/
2023-02-28 23:41:51 -03:00
protected function checkResults(): PDOStatement
2022-09-08 20:02:05 -04:00
{
2023-02-28 23:41:51 -03:00
if ($this->getStatement()->rowCount() === 0) {
throw new BlankResult(query: $this->getStatement()->queryString);
}
2023-02-28 23:41:51 -03:00
return $this->getStatement();
2022-09-08 20:02:05 -04:00
}
/**
* @return array
* @throws BlankResult
*/
2023-02-28 23:41:51 -03:00
public function fetchFirst(): array
2022-09-08 20:02:05 -04:00
{
2023-02-28 23:41:51 -03:00
return $this->checkResults()->fetch(PDO::FETCH_ASSOC);
2022-09-08 20:02:05 -04:00
}
/**
* @return array
* @throws BlankResult
*/
2023-02-28 23:41:51 -03:00
public function fetchAll(): array
{
2023-02-28 23:41:51 -03:00
return $this->checkResults()->fetchAll(PDO::FETCH_ASSOC);
}
/**
* @return object
* @throws BlankResult
*/
2023-02-28 23:41:51 -03:00
public function fetchFirstAsObject(): object
2022-09-08 20:02:05 -04:00
{
2023-02-28 23:41:51 -03:00
return $this->checkResults()->fetch(PDO::FETCH_OBJ);
}
/**
* @return array
* @throws BlankResult
*/
2023-02-28 23:41:51 -03:00
public function fetchAllAsObjects(): array
{
return $this->checkResults()->fetchAll(PDO::FETCH_OBJ);
2022-09-08 20:02:05 -04:00
}
}