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

ResultsHandler::handle()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 4
eloc 11
nc 4
nop 4
dl 0
loc 21
ccs 12
cts 12
cp 1
crap 4
rs 9.9
c 1
b 0
f 1
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