Passed
Pull Request — master (#155)
by Arnaud
36:59 queued 32:12
created

ResultsHandler::getAdapter()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 10.5

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 5
nop 1
dl 0
loc 19
ccs 5
cts 10
cp 0.5
crap 10.5
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
namespace LAG\AdminBundle\Bridge\Doctrine\ORM\Results;
4
5
use Doctrine\Common\Collections\Collection;
6
use Doctrine\ORM\Query;
7
use Doctrine\ORM\QueryBuilder;
8
use LAG\AdminBundle\Exception\Exception;
9
use Pagerfanta\Adapter\AdapterInterface;
10
use Pagerfanta\Adapter\ArrayAdapter;
11
use Pagerfanta\Adapter\DoctrineCollectionAdapter;
12
use Pagerfanta\Adapter\DoctrineORMAdapter;
13
use Pagerfanta\Pagerfanta;
14
15
class ResultsHandler implements ResultsHandlerInterface
16
{
17 4
    public function handle($data, bool $pagination, int $page = 1, int $maxPerPage = 25)
18
    {
19 4
        if ($pagination) {
20 4
            $adapter = $this->getAdapter($data);
21
22 4
            $pager = new Pagerfanta($adapter);
23 4
            $pager->setCurrentPage($page);
24 4
            $pager->setMaxPerPage($maxPerPage);
25
26 4
            return $pager;
27
        }
28
29 4
        if ($data instanceof Query) {
30 2
            return $data->getResult();
31
        }
32
33 4
        if ($data instanceof QueryBuilder) {
34 2
            return $data->getQuery()->getResult();
35
        }
36
37 2
        return $data;
38
    }
39
40 4
    private function getAdapter($data): AdapterInterface
41
    {
42 4
        if ($data instanceof QueryBuilder || $data instanceof Query) {
43 2
            return new DoctrineORMAdapter($data, true, true);
44
        }
45
46 2
        if (is_array($data)) {
47 2
            return new ArrayAdapter($data);
48
        }
49
50
        if (is_iterable($data)) {
51
            return new ArrayAdapter(iterator_to_array($data));
52
        }
53
54
        if ($data instanceof Collection) {
55
            return new DoctrineCollectionAdapter($data);
56
        }
57
58
        throw new Exception('Unable to find an adapter for type "'.gettype($data).'"');
59
    }
60
}
61