Completed
Pull Request — master (#433)
by Paul
21:53
created

QueryHelper::getQueryBuilder()   C

Complexity

Conditions 10
Paths 15

Size

Total Lines 51
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 51
rs 6
cc 10
eloc 28
nc 15
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Victoire\Bundle\QueryBundle\Helper;
4
5
use Doctrine\Common\Annotations\Reader;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\Mapping\ManyToMany;
8
use Doctrine\ORM\Mapping\ManyToOne;
9
use Doctrine\ORM\Mapping\OneToMany;
10
use Doctrine\ORM\Mapping\OneToOne;
11
use Doctrine\ORM\Query\Expr\Join;
12
use Doctrine\ORM\QueryBuilder;
13
use FOS\UserBundle\Model\UserInterface;
14
use Knp\DoctrineBehaviors\Model\Translatable\Translatable;
15
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
16
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
17
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
18
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
19
use Victoire\Bundle\CoreBundle\Entity\View;
20
use Victoire\Bundle\CoreBundle\Helper\CurrentViewHelper;
21
use Victoire\Bundle\QueryBundle\Entity\VictoireQueryInterface;
22
use Victoire\Bundle\WidgetBundle\Entity\Widget;
23
24
/**
25
 * The QueryHelper helps to build query in Victoire's components
26
 * ref: victoire_query.query_helper.
27
 */
28
class QueryHelper
29
{
30
    protected $businessEntityHelper = null;
31
    protected $currentView;
32
    protected $reader;
33
    protected $tokenStorage;
34
35
    /**
36
     * Constructor.
37
     *
38
     * @param BusinessEntityHelper $businessEntityHelper
39
     * @param CurrentViewHelper    $currentView
40
     * @param Reader               $reader
41
     */
42
    public function __construct(BusinessEntityHelper $businessEntityHelper, CurrentViewHelper $currentView, Reader $reader, TokenStorage $tokenStorage)
43
    {
44
        $this->businessEntityHelper = $businessEntityHelper;
45
        $this->currentView = $currentView;
46
        $this->reader = $reader;
47
        $this->tokenStorage = $tokenStorage;
48
    }
49
50
    /**
51
     * Get the query builder base. This makes a "select  from item XXX"
52
     * use the item for doing the left join or where dql.
53
     *
54
     * @param \Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate $containerEntity
55
     *
56
     * @throws \Exception
57
     *
58
     * @return QueryBuilder
59
     */
60
    public function getQueryBuilder(VictoireQueryInterface $containerEntity, EntityManager $em)
61
    {
62
        if ($containerEntity === null) {
63
            throw new \Exception('The container entity parameter must not be null.');
64
        }
65
66
67
        //the business name of the container entity
68
        $businessEntityId = $containerEntity->getBusinessEntityId();
69
70
        //test that there is a business entity name
71
        if ($businessEntityId === null || $businessEntityId === '') {
72
            $containerId = $containerEntity->getId();
73
            throw new \Exception('The container entity ['.$containerId.'] does not have any businessEntityId.');
74
        }
75
76
        //the business class of the container entity
77
        $businessEntity = $this->businessEntityHelper->findById(strtolower($businessEntityId));
78
79
        //test that there was a businessEntity
80
        if ($businessEntity === null) {
81
            throw new \Exception('The business entity was not found for the id:['.$businessEntityId.']');
82
        }
83
84
        $businessClass = $businessEntity->getClass();
85
86
        $itemsQueryBuilder = $em
87
            ->createQueryBuilder()
88
            ->select('main_item')
89
            ->from($businessClass, 'main_item');
90
91
        $view = $containerEntity;
92
        if ($containerEntity instanceof Widget) {
93
            $view = $containerEntity->getCurrentView();
94
        }
95
96
        if (in_array(Translatable::class, class_uses($businessClass))) {
97
            $itemsQueryBuilder->join('main_item.translations', 'translation')
98
                ->andWhere('translation.locale = :locale')
99
                ->setParameter(':locale', $view->getCurrentLocale());
0 ignored issues
show
Bug introduced by
The method getCurrentLocale does only exist in Victoire\Bundle\CoreBundle\Entity\View, but not in Victoire\Bundle\QueryBun...\VictoireQueryInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
100
        } else if ($containerEntity instanceof View && $view->getCurrentLocale() !== $view->getDefaultLocale()) {
0 ignored issues
show
Bug introduced by
The method getDefaultLocale does only exist in Victoire\Bundle\CoreBundle\Entity\View, but not in Victoire\Bundle\QueryBun...\VictoireQueryInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
101
            $itemsQueryBuilder->andWhere('1 = -1');
102
        }
103
104
        $refClass = new $businessClass();
105
        if (method_exists($refClass, 'getDeletedAt')) {
106
            $itemsQueryBuilder->andWhere('main_item.deletedAt IS NULL');
107
        }
108
109
        return $itemsQueryBuilder;
110
    }
111
112
    /**
113
     * Get the results from the sql after adding the.
114
     *
115
     * @param VictoireQueryInterface $containerEntity
116
     * @param QueryBuilder           $itemsQueryBuilder
117
     *
118
     * @throws \Exception
119
     *
120
     * @return QueryBuilder The QB to list of objects
121
     */
122
    public function buildWithSubQuery(VictoireQueryInterface $containerEntity, QueryBuilder $itemsQueryBuilder, EntityManager $em)
123
    {
124
        //get the query of the container entity
125
        $query = $containerEntity->getQuery();
126
        if (method_exists($containerEntity, 'additionnalQueryPart')) {
127
            $query = $containerEntity->additionnalQueryPart();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Victoire\Bundle\QueryBun...\VictoireQueryInterface as the method additionnalQueryPart() does only exist in the following implementations of said interface: Victoire\Bundle\BlogBundle\Entity\ArticleTemplate.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
128
        }
129
130
        if ($query !== '' && $query !== null) {
131
            $subQuery = $em->createQueryBuilder()
132
                                ->select('item.id')
133
                                ->from($itemsQueryBuilder->getRootEntities()[0], 'item');
134
135
            $itemsQueryBuilder->andWhere(
136
                sprintf('main_item.id IN (%s %s)', $subQuery->getQuery()->getDql(), $query)
137
            );
138
        }
139
140
        //Add ORDER BY if set
141
        if ($orderBy = json_decode($containerEntity->getOrderBy(), true)) {
142
            foreach ($orderBy as $addOrderBy) {
143
                $reflectionClass = new \ReflectionClass($itemsQueryBuilder->getRootEntities()[0]);
144
                $reflectionProperty = $reflectionClass->getProperty($addOrderBy['by']);
145
146
                //If ordering field is an association, treat it as a boolean
147
                if ($this->isAssociationField($reflectionProperty)) {
148
                    $itemsQueryBuilder->addSelect('CASE WHEN main_item.'.$addOrderBy['by'].' IS NULL THEN 0 ELSE 1 END AS HIDDEN caseOrder');
149
                    $itemsQueryBuilder->addOrderBy('caseOrder', $addOrderBy['order']);
150
                } else {
151
                    $itemsQueryBuilder->addOrderBy('main_item.'.$addOrderBy['by'], $addOrderBy['order']);
152
                }
153
            }
154
        }
155
156
        $currentView = $this->currentView;
157
158
        // If the current page is a BEP, we parse all its properties and inject them as query parameters
159
        if ($currentView() && $currentView() instanceof BusinessPage && null !== $currentEntity = $currentView()->getBusinessEntity()) {
160
161
            // NEW
162
            $metadatas = $em->getClassMetadata(get_class($currentEntity));
163 View Code Duplication
            foreach ($metadatas->fieldMappings as $fieldName => $field) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
164
                if (strpos($query, ':'.$fieldName) !== false) {
165
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName));
166
                }
167
            }
168 View Code Duplication
            foreach ($metadatas->associationMappings as $fieldName => $field) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
169
                if (strpos($query, ':'.$fieldName) !== false) {
170
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName)->getId());
171
                }
172
            }
173
174
            if (strpos($query, ':currentEntity') !== false) {
175
                $itemsQueryBuilder->setParameter('currentEntity', $currentEntity->getId());
176
            }
177
        }
178
179
        if (strpos($query, ':currentUser') !== false && is_object($this->getCurrentUser())) {
180
            if (is_object($this->getCurrentUser())) {
181
                $itemsQueryBuilder->setParameter('currentUser', $this->getCurrentUser()->getId());
182
            } else {
183
                throw new AccessDeniedException();
184
            }
185
        }
186
187
        return $itemsQueryBuilder;
188
    }
189
190
    /**
191
     * Check if field is a OneToOne, OneToMany, ManyToOne or ManyToMany association.
192
     *
193
     * @param \ReflectionProperty $field
194
     *
195
     * @return bool
196
     */
197
    private function isAssociationField(\ReflectionProperty $field)
198
    {
199
        $annotations = $this->reader->getPropertyAnnotations($field);
200
        foreach ($annotations as $key => $annotationObj) {
201
            if ($annotationObj instanceof OneToOne || $annotationObj instanceof OneToMany || $annotationObj instanceof ManyToOne || $annotationObj instanceof ManyToMany) {
202
                return true;
203
            }
204
        }
205
206
        return false;
207
    }
208
209
    /**
210
     * @return UserInterface|string
211
     */
212
    public function getCurrentUser()
213
    {
214
        return $this->tokenStorage->getToken()->getUser();
215
    }
216
}
217