<?php

declare(strict_types=1);

namespace App\Framework\Database;

use App\Framework\Database\ResultInterface;

final class PdoResult implements ResultInterface
{
    private \PDOStatement $statement;
    private ?array $rows = null;

    public function __construct(\PDOStatement $statement)
    {
        $this->statement = $statement;
    }

    public function fetch(): ?array
    {
        $row = $this->statement->fetch();
        return $row === false ? null : $row;
    }

    public function fetchAll(): array
    {
        if ($this->rows === null) {
            $this->rows = $this->statement->fetchAll();
        }

        return $this->rows;
    }

    public function fetchColumn(int $column = 0): array
    {
        return $this->statement->fetchAll(\PDO::FETCH_COLUMN, $column);
    }

    public function fetchScalar(): mixed
    {
        $value = $this->statement->fetchColumn();
        return $value === false ? null : $value;
    }

    public function rowCount(): int
    {
        return $this->statement->rowCount();
    }

    public function count(): int
    {
        return count($this->fetchAll());
    }

    public function getIterator(): \ArrayIterator
    {
        return new \ArrayIterator($this->fetchAll());
    }
}
