Completed
Push — master ( 0febda...d683d0 )
by Antoine
17s
created

QueryBuilderHelper   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 9
lcom 0
cbo 4
dl 0
loc 52
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A addJoinOnce() 0 19 4
A getExistingJoin() 0 17 4
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Util;
15
16
use Doctrine\ORM\Query\Expr\Join;
17
use Doctrine\ORM\QueryBuilder;
18
19
/**
20
 * @author Vincent Chalamon <[email protected]>
21
 *
22
 * @internal
23
 */
24
final class QueryBuilderHelper
25
{
26
    private function __construct()
27
    {
28
    }
29
30
    /**
31
     * Adds a join to the queryBuilder if none exists.
32
     */
33
    public static function addJoinOnce(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $alias, string $association, string $joinType = null, string $conditionType = null, string $condition = null): string
34
    {
35
        $join = self::getExistingJoin($queryBuilder, $alias, $association);
36
37
        if (null !== $join) {
38
            return $join->getAlias();
39
        }
40
41
        $associationAlias = $queryNameGenerator->generateJoinAlias($association);
42
        $query = "$alias.$association";
43
44
        if (Join::LEFT_JOIN === $joinType || QueryChecker::hasLeftJoin($queryBuilder)) {
45
            $queryBuilder->leftJoin($query, $associationAlias, $conditionType, $condition);
46
        } else {
47
            $queryBuilder->innerJoin($query, $associationAlias, $conditionType, $condition);
48
        }
49
50
        return $associationAlias;
51
    }
52
53
    /**
54
     * Get the existing join from queryBuilder DQL parts.
55
     *
56
     * @return Join|null
57
     */
58
    private static function getExistingJoin(QueryBuilder $queryBuilder, string $alias, string $association)
59
    {
60
        $parts = $queryBuilder->getDQLPart('join');
61
62
        if (!isset($parts['o'])) {
63
            return null;
64
        }
65
66
        foreach ($parts['o'] as $join) {
67
            /** @var Join $join */
68
            if (sprintf('%s.%s', $alias, $association) === $join->getJoin()) {
69
                return $join;
70
            }
71
        }
72
73
        return null;
74
    }
75
}
76