Completed
Pull Request — master (#155)
by Arnaud
38:29
created

ResultsHandler::getAdapter()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 9
nc 5
nop 1
dl 0
loc 19
ccs 0
cts 0
cp 0
crap 42
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 4
use Pagerfanta\Pagerfanta;
14
15 4
class ResultsHandler implements ResultsHandlerInterface
16 4
{
17 2
    public function handle($data, bool $pagination, int $page = 1, int $maxPerPage = 25)
18
    {
19 2
        if ($pagination) {
20
            $adapter = $this->getAdapter($data);
21 4
22 4
            $pager = new Pagerfanta($adapter);
23 4
            $pager->setCurrentPage($page);
24
            $pager->setMaxPerPage($maxPerPage);
25 4
26
            return $pager;
27
        }
28 4
29 2
        if ($data instanceof Query) {
30
            return $data->getResult();
31
        }
32 4
33 2
        if ($data instanceof QueryBuilder) {
34
            return $data->getQuery()->getResult();
35
        }
36 2
37
        return $data;
38
    }
39
40
    private function getAdapter($data): AdapterInterface
41
    {
42
        if ($data instanceof QueryBuilder || $data instanceof Query) {
43
            return new DoctrineORMAdapter($data, true, true);
44
        }
45
46
        if (is_array($data)) {
47
            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