Completed
Push — master ( 1fe708...6360f1 )
by Arnaud
16s queued 12s
created

ResultsHandler   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 12
eloc 24
c 1
b 1
f 0
dl 0
loc 53
ccs 26
cts 26
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getAdapter() 0 19 6
A supports() 0 3 1
A handle() 0 25 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LAG\AdminBundle\Bridge\Doctrine\DataHandler;
6
7
use Doctrine\Common\Collections\ArrayCollection;
8
use Doctrine\Common\Collections\Collection;
9
use Doctrine\ORM\Query;
10
use Doctrine\ORM\QueryBuilder;
11
use LAG\AdminBundle\Bridge\Doctrine\DataSource\ORMDataSource;
12
use LAG\AdminBundle\DataProvider\DataSourceHandler\DataHandlerInterface;
13
use LAG\AdminBundle\DataProvider\DataSourceInterface;
14
use LAG\AdminBundle\Exception\Exception;
15
use Pagerfanta\Adapter\AdapterInterface;
16
use Pagerfanta\Adapter\ArrayAdapter;
17
use Pagerfanta\Doctrine\Collections\CollectionAdapter;
18
use Pagerfanta\Doctrine\ORM\QueryAdapter;
19
use Pagerfanta\Pagerfanta;
20
21
class ResultsHandler implements DataHandlerInterface
22
{
23 2
    public function supports(DataSourceInterface $dataSource): bool
24
    {
25 2
        return $dataSource instanceof ORMDataSource;
26
    }
27
28 9
    public function handle(DataSourceInterface $dataSource)
29
    {
30 9
        if ($dataSource->isPaginated()) {
31 5
            $adapter = $this->getAdapter($dataSource->getData());
32
33 4
            $pager = new Pagerfanta($adapter);
34 4
            $pager->setCurrentPage($dataSource->getPage());
35 4
            $pager->setMaxPerPage($dataSource->getMaxPerPage());
36
37 4
            return $pager;
38
        }
39
40 4
        if ($dataSource->getData() instanceof Query) {
41 1
            return $dataSource->getData()->getResult();
42
        }
43
44 3
        if ($dataSource->getData() instanceof QueryBuilder) {
45 1
            return $dataSource->getData()->getQuery()->getResult();
46
        }
47
48 2
        if (\is_array($dataSource->getData())) {
49 1
            return new ArrayCollection($dataSource->getData());
50
        }
51
52 1
        return $dataSource->getData();
53
    }
54
55 5
    private function getAdapter($data): AdapterInterface
56
    {
57 5
        if ($data instanceof QueryBuilder || $data instanceof Query) {
58 1
            return new QueryAdapter($data, true, true);
59
        }
60
61 4
        if ($data instanceof Collection) {
62 1
            return new CollectionAdapter($data);
63
        }
64
65 3
        if (\is_array($data)) {
66 1
            return new ArrayAdapter($data);
67
        }
68
69 2
        if (is_iterable($data)) {
70 1
            return new ArrayAdapter(iterator_to_array($data));
71
        }
72
73 1
        throw new Exception('Unable to find an adapter for type "'.\gettype($data).'"');
74
    }
75
}
76