Completed
Push — master ( dd5924...1cc36f )
by Joachim
62:06 queued 54:44
created

EntityRepository::findAllWithPaging()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 4
nop 4
1
<?php
2
3
namespace Loevgaard\PakkelabelsBundle\Entity;
4
5
use Doctrine\Common\Persistence\ManagerRegistry;
6
use Doctrine\ORM\EntityRepository as DoctrineEntityRepository;
7
use Doctrine\ORM\QueryBuilder;
8
use Knp\Component\Pager\Pagination\PaginationInterface;
9
use Knp\Component\Pager\PaginatorInterface;
10
11
/**
12
 * This entity repository is implemented using the principles described here:
13
 * https://www.tomasvotruba.cz/blog/2017/10/16/how-to-use-repository-with-doctrine-as-service-in-symfony/
14
 *
15
 * @todo this class should probably be in a separate library
16
 *
17
 * @method array findBy(array $criteria, array $orderBy = null, int $limit = null, int $offset = null)
18
 * @method null|object findOneBy(array $criteria)
19
 * @method array findAll()
20
 */
21
abstract class EntityRepository
22
{
23
    /**
24
     * @var DoctrineEntityRepository
25
     */
26
    protected $repository;
27
28
    /**
29
     * @var PaginatorInterface
30
     */
31
    protected $paginator;
32
33
    public function __construct(ManagerRegistry $managerRegistry, PaginatorInterface $paginator, string $class) {
34
        $this->repository = $managerRegistry
35
            ->getManagerForClass($class)
36
            ->getRepository($class)
37
        ;
38
39
        $this->paginator = $paginator;
40
    }
41
42
    /**
43
     * @param string $name
44
     * @param array $arguments
45
     * @return mixed
46
     */
47
    public function __call($name, $arguments)
48
    {
49
        if (method_exists($this->repository, $name)) {
50
            return call_user_func_array([$this->repository, $name], $arguments);
51
        }
52
    }
53
54
    /**
55
     * @param int $page
56
     * @param int $itemsPerPage
57
     * @param array $orderBy
58
     * @param QueryBuilder $qb
59
     * @return PaginationInterface
60
     */
61
    public function findAllWithPaging($page = 1, $itemsPerPage = 100, array $orderBy = [], QueryBuilder $qb = null) : PaginationInterface
62
    {
63
        if(!$qb) {
64
            $qb = $this->getQueryBuilder('e');
65
        }
66
67
        foreach ($orderBy as $field => $direction) {
68
            $qb->addOrderBy($field, $direction);
69
        }
70
71
        $objs = $this->paginator->paginate(
72
            $qb,
73
            $page,
74
            $itemsPerPage
75
        );
76
77
        return $objs;
78
    }
79
80
    /**
81
     * @param string $alias
82
     * @return QueryBuilder
83
     */
84
    public function getQueryBuilder(string $alias) : QueryBuilder
85
    {
86
        return $this->repository->createQueryBuilder($alias);
87
    }
88
}
89