Completed
Push — master ( 0e1368...c48087 )
by Sam
05:46
created

Helper::paginate()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 1
nop 2
dl 0
loc 16
ccs 11
cts 11
cp 1
crap 2
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Api;
6
7
use Application\Acl\Acl;
8
use Application\Model\AbstractModel;
9
use Doctrine\ORM\QueryBuilder;
10
use Doctrine\ORM\Tools\Pagination\Paginator;
11
use GraphQL\Doctrine\Definition\EntityID;
12
13
abstract class Helper
14
{
15 4
    public static function throwIfDenied(AbstractModel $model, string $privilege): void
16
    {
17 4
        $acl = new Acl();
18 4
        if (!$acl->isCurrentUserAllowed($model, $privilege)) {
19 1
            throw new Exception($acl->getLastDenialMessage());
20
        }
21 3
    }
22
23 1
    public static function paginate(array $pagination, QueryBuilder $query): array
24
    {
25 1
        $offset = $pagination['offset'] ?? 0;
26 1
        $pageIndex = $pagination['pageIndex'] ?? 0;
27 1
        $pageSize = $pagination['pageSize'];
28
29 1
        $paginator = new Paginator($query);
30
        $paginator
31 1
            ->getQuery()
32 1
            ->setFirstResult($offset ? $offset : $pageSize * $pageIndex)
33 1
            ->setMaxResults($pageSize);
34
35 1
        $pagination['length'] = $paginator->count();
36 1
        $pagination['items'] = $paginator->getIterator();
37
38 1
        return $pagination;
39
    }
40
41 1
    public static function hydrate(AbstractModel $object, array $input): void
42
    {
43 1
        foreach ($input as $name => $value) {
44 1
            if ($value instanceof EntityID) {
45
                $value = $value->getEntity();
46
            }
47
48 1
            $setter = 'set' . ucfirst($name);
49 1
            $object->$setter($value);
50
        }
51 1
    }
52
}
53