Completed
Push — master ( 6c3bf7...0f5529 )
by Kevin
02:05
created

DBALQueryBuilderResult::getIterator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
3
namespace Zenstruck\Porpaginas\Doctrine\DBAL;
4
5
use Doctrine\DBAL\Query\QueryBuilder;
6
use Zenstruck\Porpaginas\Callback\CallbackPage;
7
use Zenstruck\Porpaginas\Result;
8
9
/**
10
 * @author Kevin Bond <[email protected]>
11
 */
12
final class DBALQueryBuilderResult implements Result
13
{
14
    private $qb;
15
    private $count;
16
17
    public function __construct(QueryBuilder $qb)
18
    {
19
        $this->qb = $qb;
20
    }
21
22
    /**
23
     * {@inheritdoc}
24
     */
25
    public function take($offset, $limit)
26
    {
27
        $qb = clone $this->qb;
28
        $results = function ($offset, $limit) use ($qb) {
29
            return $qb
30
                ->setFirstResult($offset)
31
                ->setMaxResults($limit)
32
                ->execute()
33
                ->fetchAll();
34
        };
35
36
        return new CallbackPage($results, [$this, 'count'], $offset, $limit);
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function count()
43
    {
44
        if ($this->count !== null) {
45
            return $this->count;
46
        }
47
48
        $qb = clone $this->qb;
49
        $stmt = $qb->select('COUNT(*) as cnt')
50
            ->orderBy('cnt')
51
            ->execute();
52
53
        return $this->count = (int) $stmt->fetch(\PDO::FETCH_COLUMN);
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function getIterator()
60
    {
61
        $stmt = $this->qb->execute();
62
63
        while ($data = $stmt->fetch()) {
64
            yield $data;
65
        }
66
    }
67
}
68