Passed
Push — master ( 3e489f...b209ea )
by Adrien
07:16
created

Helper   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 63
ccs 33
cts 33
cp 1
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A paginate() 0 16 2
A throwIfDenied() 0 5 2
A hydrate() 0 9 3
A aggregatedFields() 0 15 2
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 Application\Model\Booking;
10
use Doctrine\ORM\QueryBuilder;
11
use Doctrine\ORM\Tools\Pagination\Paginator;
12
use GraphQL\Doctrine\Definition\EntityID;
13
14
abstract class Helper
15
{
16 10
    public static function throwIfDenied(AbstractModel $model, string $privilege): void
17
    {
18 10
        $acl = new Acl();
19 10
        if (!$acl->isCurrentUserAllowed($model, $privilege)) {
20 1
            throw new Exception($acl->getLastDenialMessage());
21
        }
22 9
    }
23
24 3
    public static function paginate(array $pagination, QueryBuilder $query): array
25
    {
26 3
        $offset = $pagination['offset'] ?? 0;
27 3
        $pageIndex = $pagination['pageIndex'] ?? 0;
28 3
        $pageSize = $pagination['pageSize'];
29
30 3
        $paginator = new Paginator($query);
31
        $paginator
32 3
            ->getQuery()
33 3
            ->setFirstResult($offset ? $offset : $pageSize * $pageIndex)
34 3
            ->setMaxResults($pageSize);
35
36 3
        $pagination['length'] = $paginator->count();
37 3
        $pagination['items'] = $paginator->getIterator();
38
39 3
        return $pagination;
40
    }
41
42 6
    public static function hydrate(AbstractModel $object, array $input): void
43
    {
44 6
        foreach ($input as $name => $value) {
45 6
            if ($value instanceof EntityID) {
46 1
                $value = $value->getEntity();
47
            }
48
49 6
            $setter = 'set' . ucfirst($name);
50 6
            $object->$setter($value);
51
        }
52 6
    }
53
54
    /**
55
     * Returns aggregated fields (as scalar) for the given QueryBuilder
56
     *
57
     * @param string $class
58
     * @param QueryBuilder $qb
59
     *
60
     * @return array
61
     */
62 3
    public static function aggregatedFields(string $class, QueryBuilder $qb): array
63
    {
64 3
        $result = [];
65
66 3
        if ($class === Booking::class) {
67 1
            $qb->resetDQLPart('select')
68 1
                ->addSelect('SUM(booking1.participantCount) AS totalParticipantCount')
69 1
                ->addSelect('SUM(bookable.periodicPrice) AS totalPeriodicPrice')
70 1
                ->addSelect('SUM(bookable.initialPrice) AS totalInitialPrice')
71 1
                ->leftJoin('booking1.bookables', 'bookable');
72
73 1
            $result = $qb->getQuery()->getResult()[0];
74
        }
75
76 3
        return $result;
77
    }
78
}
79