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

DBALQueryBuilderResult   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 92.31%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 63
ccs 24
cts 26
cp 0.9231
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 2
A take() 0 13 1
A count() 0 12 2
A getIterator() 0 8 2
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