Completed
Push — master ( d259d9...b8aac0 )
by Kevin
02:33
created

DBALQueryBuilderResult::count()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
ccs 5
cts 6
cp 0.8333
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
crap 2.0185
1
<?php
2
3
namespace Zenstruck\Porpaginas\Doctrine;
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 $countQueryBuilderModifier;
16
    private $count;
17
18
    /**
19
     * @param QueryBuilder  $qb
20
     * @param callable|null $countQueryBuilderModifier
21
     */
22 12
    public function __construct(QueryBuilder $qb, callable $countQueryBuilderModifier = null)
23
    {
24 12
        $this->qb = $qb;
25
        $this->countQueryBuilderModifier = $countQueryBuilderModifier ?: function (QueryBuilder $qb) {
26 4
            return $qb->select('COUNT(*)');
27
        };
28 12
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 4
    public function take($offset, $limit)
34
    {
35 4
        $qb = clone $this->qb;
36 4
        $results = function ($offset, $limit) use ($qb) {
37
            return $qb
38 4
                ->setFirstResult($offset)
39 4
                ->setMaxResults($limit)
40 4
                ->execute()
41 4
                ->fetchAll();
42 4
        };
43
44 4
        return new CallbackPage($results, [$this, 'count'], $offset, $limit);
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 4
    public function count()
51
    {
52 4
        if ($this->count !== null) {
53
            return $this->count;
54
        }
55
56 4
        $qb = clone $this->qb;
57
58 4
        call_user_func($this->countQueryBuilderModifier, $qb);
59
60 4
        return $this->count = (int) $qb->execute()->fetchColumn();
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66 1
    public function getIterator()
67
    {
68 1
        $stmt = $this->qb->execute();
69
70 1
        while ($data = $stmt->fetch()) {
71 1
            yield $data;
72 1
        }
73 1
    }
74
}
75