Passed
Pull Request — master (#259)
by Arnaud
08:22
created

ResultsHandler   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

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