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

ResultsHandler   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 21
dl 0
loc 44
ccs 13
cts 13
cp 1
rs 10
c 1
b 0
f 1
wmc 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 21 4
A getAdapter() 0 19 6
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