Completed
Push — master ( efa664...ac0835 )
by Joachim
15:34
created

EntityRepository::findAllWithPaging()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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