summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/sql/src/Cursor.php
blob: 85c5b1c87f5056b8661daea17dabe2189efd1425 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php

namespace ipl\Sql;

use ipl\Stdlib\Contract\Paginatable;
use IteratorAggregate;
use Traversable;

/**
 * Cursor for ipl SQL queries
 */
class Cursor implements IteratorAggregate, Paginatable
{
    /** @var Connection */
    protected $db;

    /** @var Select */
    protected $select;

    /** @var array */
    protected $fetchModeAndArgs = [];

    /**
     * Create a new cursor for the given connection and query
     *
     * @param Connection $db
     * @param Select     $select
     */
    public function __construct(Connection $db, Select $select)
    {
        $this->db = $db;
        $this->select = $select;
    }

    /**
     * Get the fetch mode
     *
     * @return array
     */
    public function getFetchMode()
    {
        return $this->fetchModeAndArgs;
    }

    /**
     * Set the fetch mode
     *
     * @param int   $fetchMode Fetch mode as one of the PDO fetch mode constants.
     *                         Please see {@link https://www.php.net/manual/en/pdostatement.setfetchmode} for details
     * @param mixed ...$args   Fetch mode arguments
     *
     * @return $this
     */
    public function setFetchMode($fetchMode, ...$args)
    {
        array_unshift($args, $fetchMode);

        $this->fetchModeAndArgs = $args;

        return $this;
    }

    public function getIterator(): Traversable
    {
        return $this->db->yieldAll($this->select, ...$this->getFetchMode());
    }

    public function hasLimit()
    {
        return $this->select->hasLimit();
    }

    public function getLimit()
    {
        return $this->select->getLimit();
    }

    public function limit($limit)
    {
        $this->select->limit($limit);

        return $this;
    }

    public function hasOffset()
    {
        return $this->select->hasOffset();
    }

    public function getOffset()
    {
        return $this->select->getOffset();
    }

    public function offset($offset)
    {
        $this->select->offset($offset);

        return $this;
    }

    public function count(): int
    {
        return $this->db->select($this->select->getCountQuery())->fetchColumn(0);
    }
}