Completed
Push — master ( 5d51b4...87fdd9 )
by Paul
10s
created

QueryHelper::getQueryBuilder()   C

Complexity

Conditions 10
Paths 15

Size

Total Lines 52
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 52
rs 6.2553
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 = null;
92
        if ($containerEntity instanceof View) {
93
            $view = $containerEntity;
94
        } elseif ($containerEntity instanceof Widget) {
95
            $view = $containerEntity->getCurrentView();
96
        }
97
98
        // when the businessClass is translatable, join translations for the current locale
99
        if ($view && in_array(Translatable::class, class_uses($businessClass))) {
100
            $itemsQueryBuilder->join('main_item.translations', 'translation')
101
                ->andWhere('translation.locale = :locale')
102
                ->setParameter(':locale', $view->getCurrentLocale());
103
        }
104
105
        $refClass = new $businessClass();
106
        if (method_exists($refClass, 'getDeletedAt')) {
107
            $itemsQueryBuilder->andWhere('main_item.deletedAt IS NULL');
108
        }
109
110
        return $itemsQueryBuilder;
111
    }
112
113
    /**
114
     * Get the results from the sql after adding the.
115
     *
116
     * @param VictoireQueryInterface $containerEntity
117
     * @param QueryBuilder           $itemsQueryBuilder
118
     *
119
     * @throws \Exception
120
     *
121
     * @return QueryBuilder The QB to list of objects
122
     */
123
    public function buildWithSubQuery(VictoireQueryInterface $containerEntity, QueryBuilder $itemsQueryBuilder, EntityManager $em)
124
    {
125
        //get the query of the container entity
126
        $query = $containerEntity->getQuery();
127
        if (method_exists($containerEntity, 'additionnalQueryPart')) {
128
            $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...
129
        }
130
131
        if ($query !== '' && $query !== null) {
132
            $subQuery = $em->createQueryBuilder()
133
                                ->select('item.id')
134
                                ->from($itemsQueryBuilder->getRootEntities()[0], 'item');
135
136
            $itemsQueryBuilder->andWhere(
137
                sprintf('main_item.id IN (%s %s)', $subQuery->getQuery()->getDql(), $query)
138
            );
139
        }
140
141
        //Add ORDER BY if set
142
        if ($orderBy = json_decode($containerEntity->getOrderBy(), true)) {
143
            foreach ($orderBy as $addOrderBy) {
144
                $reflectionClass = new \ReflectionClass($itemsQueryBuilder->getRootEntities()[0]);
145
                $reflectionProperty = $reflectionClass->getProperty($addOrderBy['by']);
146
147
                //If ordering field is an association, treat it as a boolean
148
                if ($this->isAssociationField($reflectionProperty)) {
149
                    $itemsQueryBuilder->addSelect('CASE WHEN main_item.'.$addOrderBy['by'].' IS NULL THEN 0 ELSE 1 END AS HIDDEN caseOrder');
150
                    $itemsQueryBuilder->addOrderBy('caseOrder', $addOrderBy['order']);
151
                } else {
152
                    $itemsQueryBuilder->addOrderBy('main_item.'.$addOrderBy['by'], $addOrderBy['order']);
153
                }
154
            }
155
        }
156
157
        $currentView = $this->currentView;
158
159
        // If the current page is a BEP, we parse all its properties and inject them as query parameters
160
        if ($currentView() && $currentView() instanceof BusinessPage && null !== $currentEntity = $currentView()->getBusinessEntity()) {
161
162
            // NEW
163
            $metadatas = $em->getClassMetadata(get_class($currentEntity));
164 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...
165
                if (strpos($query, ':'.$fieldName) !== false) {
166
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName));
167
                }
168
            }
169 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...
170
                if (strpos($query, ':'.$fieldName) !== false) {
171
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName)->getId());
172
                }
173
            }
174
175
            if (strpos($query, ':currentEntity') !== false) {
176
                $itemsQueryBuilder->setParameter('currentEntity', $currentEntity->getId());
177
            }
178
        }
179
180
        if (strpos($query, ':currentUser') !== false && is_object($this->getCurrentUser())) {
181
            if (is_object($this->getCurrentUser())) {
182
                $itemsQueryBuilder->setParameter('currentUser', $this->getCurrentUser()->getId());
183
            } else {
184
                throw new AccessDeniedException();
185
            }
186
        }
187
188
        return $itemsQueryBuilder;
189
    }
190
191
    /**
192
     * Check if field is a OneToOne, OneToMany, ManyToOne or ManyToMany association.
193
     *
194
     * @param \ReflectionProperty $field
195
     *
196
     * @return bool
197
     */
198
    private function isAssociationField(\ReflectionProperty $field)
199
    {
200
        $annotations = $this->reader->getPropertyAnnotations($field);
201
        foreach ($annotations as $key => $annotationObj) {
202
            if ($annotationObj instanceof OneToOne || $annotationObj instanceof OneToMany || $annotationObj instanceof ManyToOne || $annotationObj instanceof ManyToMany) {
203
                return true;
204
            }
205
        }
206
207
        return false;
208
    }
209
210
    /**
211
     * @return UserInterface|string
212
     */
213
    public function getCurrentUser()
214
    {
215
        return $this->tokenStorage->getToken()->getUser();
216
    }
217
}
218