OrderLineRepository::createPurchaseQueryBuilder()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 3.0032

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 13
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 23
ccs 13
cts 14
cp 0.9286
crap 3.0032
rs 9.8333
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Repository;
6
7
use Application\Api\Field\Standard;
8
use Application\Enum\OrderStatus;
9
use Application\Model\OrderLine;
10
use Application\Model\Product;
11
use Application\Model\User;
12
use Doctrine\ORM\Query\Expr\Join;
13
use Doctrine\ORM\Query\Parameter;
14
use Doctrine\ORM\QueryBuilder;
15
16
use Ecodev\Felix\Repository\LimitedAccessSubQuery;
17
18
/**
19
 * @extends AbstractRepository<OrderLine>
20
 */
21
class OrderLineRepository extends AbstractRepository implements LimitedAccessSubQuery
22
{
23
    /**
24
     * Returns pure SQL to get ID of all objects that are accessible to given user.
25
     *
26
     * @param null|User $user
27
     */
28 10
    public function getAccessibleSubQuery(?\Ecodev\Felix\Model\User $user): string
29
    {
30 10
        if (!$user) {
31 1
            return '-1';
32
        }
33
34 9
        if (in_array($user->getRole(), [User::ROLE_FACILITATOR, User::ROLE_ADMINISTRATOR], true)) {
35 3
            return '';
36
        }
37
38 6
        return $this->getAllIdsForOwnerQuery($user);
39
    }
40
41 1
    public function createPurchaseQueryBuilder(array $filters, array $sortings): QueryBuilder
42
    {
43 1
        $qbProduct = _types()->createFilteredQueryBuilder(Product::class, Standard::customTypesToScalar($filters), []);
44
45 1
        $qb = $this->createQueryBuilder('orderLine')
46 1
            ->addSelect('product')
47 1
            ->innerJoin('orderLine.order', 'o', Join::WITH, 'o.status = :status AND o.owner = :user')
48 1
            ->innerJoin('orderLine.product', 'product', Join::WITH, 'product.isActive = TRUE')
49 1
            ->andWhere('orderLine.product IN (' . $qbProduct->getDQL() . ')')
50 1
            ->setParameter('status', OrderStatus::Validated->value)
51 1
            ->setParameter('user', User::getCurrent());
52
53
        // Apply sort on products
54 1
        foreach ($sortings as $sorting) {
55 1
            $qb->addOrderBy('product.' . $sorting['field'], $sorting['order']);
56
        }
57
58
        /** @var Parameter $parameter */
59 1
        foreach ($qbProduct->getParameters() as $parameter) {
60
            $qb->setParameter($parameter->getName(), $parameter->getValue(), $parameter->getType());
61
        }
62
63 1
        return $qb;
64
    }
65
}
66