QueryHelper   B
last analyzed

Complexity

Total Complexity 39

Size/Duplication

Total Lines 203
Duplicated Lines 4.93 %

Coupling/Cohesion

Components 2
Dependencies 12

Importance

Changes 0
Metric Value
wmc 39
lcom 2
cbo 12
dl 10
loc 203
rs 8.2857
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
C getQueryBuilder() 0 56 11
C buildWithSubQuery() 10 69 20
B isAssociationField() 0 11 6
A getCurrentUser() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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\EntityRepository;
8
use Doctrine\ORM\Mapping\ManyToMany;
9
use Doctrine\ORM\Mapping\ManyToOne;
10
use Doctrine\ORM\Mapping\OneToMany;
11
use Doctrine\ORM\Mapping\OneToOne;
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\BusinessPageBundle\Entity\BusinessTemplate;
20
use Victoire\Bundle\CoreBundle\Entity\View;
21
use Victoire\Bundle\CoreBundle\Helper\CurrentViewHelper;
22
use Victoire\Bundle\QueryBundle\Entity\VictoireQueryInterface;
23
use Victoire\Bundle\WidgetBundle\Entity\Widget;
24
25
/**
26
 * The QueryHelper helps to build query in Victoire's components
27
 * ref: victoire_query.query_helper.
28
 */
29
class QueryHelper
30
{
31
    protected $businessEntityHelper = null;
32
    protected $currentView;
33
    protected $reader;
34
    protected $tokenStorage;
35
    /**
36
     * @var EntityRepository
37
     */
38
    private $businessEntityRepository;
39
40
    /**
41
     * Constructor.
42
     *
43
     * @param BusinessEntityHelper $businessEntityHelper
44
     * @param CurrentViewHelper    $currentView
45
     * @param Reader               $reader
46
     * @param TokenStorage         $tokenStorage
47
     * @param EntityRepository     $businessEntityRepository
48
     */
49
    public function __construct(BusinessEntityHelper $businessEntityHelper, CurrentViewHelper $currentView, Reader $reader, TokenStorage $tokenStorage, EntityRepository $businessEntityRepository)
50
    {
51
        $this->businessEntityHelper = $businessEntityHelper;
52
        $this->currentView = $currentView;
53
        $this->reader = $reader;
54
        $this->tokenStorage = $tokenStorage;
55
        $this->businessEntityRepository = $businessEntityRepository;
56
    }
57
58
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$em" missing
Loading history...
59
     * Get the query builder base. This makes a "select  from item XXX"
60
     * use the item for doing the left join or where dql.
61
     *
62
     * @param \Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate $containerEntity
63
     *
64
     * @throws \Exception
65
     *
66
     * @return QueryBuilder
67
     */
68
    public function getQueryBuilder(VictoireQueryInterface $containerEntity, EntityManager $em)
69
    {
70
        if ($containerEntity === null) {
71
            throw new \Exception('The container entity parameter must not be null.');
72
        }
73
74
        //the business name of the container entity
75
        if ($containerEntity->getBusinessEntity()) {
76
            $businessEntity = $containerEntity->getBusinessEntity();
77
        } else {
78
            $businessEntity = $containerEntity->getEntityProxy()->getBusinessEntity();
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 getEntityProxy() does only exist in the following implementations of said interface: Victoire\Bundle\WidgetBundle\Entity\Widget, Victoire\Widget\ForceBundle\Entity\WidgetForce, Victoire\Widget\LightSab...Entity\WidgetLightSaber.

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...
79
        }
80
        $businessEntityId = $businessEntity->getName();
81
82
        //test that there is a business entity name
83
        if ($businessEntityId === null || $businessEntityId === '') {
84
            $containerId = $containerEntity->getId();
85
            throw new \Exception('The container entity ['.$containerId.'] does not have any businessEntityId.');
86
        }
87
88
        //the business class of the container entity
89
        $businessEntity = $this->businessEntityRepository->findOneBy(['name' => strtolower($businessEntityId)]);
90
        //test that there was a businessEntity
91
        if ($businessEntity === null) {
92
            throw new \Exception('The business entity was not found for the id:['.$businessEntityId.']');
93
        }
94
95
        $businessClass = $businessEntity->getClass();
96
97
        $itemsQueryBuilder = $em
98
            ->createQueryBuilder()
99
            ->select('main_item')
100
            ->from($businessClass, 'main_item')
101
            ->andWhere('main_item.visibleOnFront = 1');
102
103
        $view = null;
104
        if ($containerEntity instanceof View) {
105
            $view = $containerEntity;
106
        } elseif ($containerEntity instanceof Widget) {
107
            $view = $containerEntity->getCurrentView();
108
        }
109
110
        // when the businessClass is translatable, join translations for the current locale
111
        if ($view && in_array(Translatable::class, class_uses($businessClass))) {
112
            $itemsQueryBuilder->join('main_item.translations', 'translation')
113
                ->andWhere('translation.locale = :locale')
114
                ->setParameter(':locale', $view->getCurrentLocale());
115
        }
116
117
        $refClass = new \ReflectionClass($businessClass);
118
        if ($refClass->hasMethod('getDeletedAt')) {
119
            $itemsQueryBuilder->andWhere('main_item.deletedAt IS NULL');
120
        }
121
122
        return $itemsQueryBuilder;
123
    }
124
125
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$em" missing
Loading history...
126
     * Get the results from the sql after adding the.
127
     *
128
     * @param VictoireQueryInterface $containerEntity
129
     * @param QueryBuilder           $itemsQueryBuilder
130
     *
131
     * @throws \Exception
132
     *
133
     * @return QueryBuilder The QB to list of objects
134
     */
135
    public function buildWithSubQuery(VictoireQueryInterface $containerEntity, QueryBuilder $itemsQueryBuilder, EntityManager $em)
136
    {
137
        //get the query of the container entity
138
        $query = $containerEntity->getQuery();
139
        if (method_exists($containerEntity, 'additionnalQueryPart')) {
140
            $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...
141
        }
142
143
        if ($query !== '' && $query !== null) {
144
            $subQuery = $em->createQueryBuilder()
145
                                ->select('item.id')
146
                                ->from($itemsQueryBuilder->getRootEntities()[0], 'item');
147
148
            $itemsQueryBuilder->andWhere(
149
                sprintf('main_item.id IN (%s %s)', $subQuery->getQuery()->getDql(), $query)
150
            );
151
        }
152
153
        //Add ORDER BY if set
154
        if ($orderBy = json_decode($containerEntity->getOrderBy(), true)) {
155
            foreach ($orderBy as $addOrderBy) {
156
                $reflectionClass = new \ReflectionClass($itemsQueryBuilder->getRootEntities()[0]);
157
                $reflectionProperty = $reflectionClass->getProperty($addOrderBy['by']);
158
159
                //If ordering field is an association, treat it as a boolean
160
                if ($this->isAssociationField($reflectionProperty)) {
161
                    $itemsQueryBuilder->addSelect('CASE WHEN main_item.'.$addOrderBy['by'].' IS NULL THEN 0 ELSE 1 END AS HIDDEN caseOrder');
162
                    $itemsQueryBuilder->addOrderBy('caseOrder', $addOrderBy['order']);
163
                } else {
164
                    $itemsQueryBuilder->addOrderBy('main_item.'.$addOrderBy['by'], $addOrderBy['order']);
165
                }
166
            }
167
        }
168
169
        $currentView = $this->currentView;
170
171
        // If the current page is a BEP, we parse all its properties and inject them as query parameters
172
        if ($currentView() && $currentView() instanceof BusinessPage && null !== $currentEntity = $currentView()->getBusinessEntity()) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
173
174
            // NEW
175
            $metadatas = $em->getClassMetadata(get_class($currentEntity));
176 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...
177
                if (strpos($query, ':'.$fieldName) !== false) {
178
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName));
179
                }
180
            }
181 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...
182
                if (strpos($query, ':'.$fieldName) !== false) {
183
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName)->getId());
184
                }
185
            }
186
187
            if (strpos($query, ':currentEntity') !== false) {
188
                $itemsQueryBuilder->setParameter('currentEntity', $currentEntity->getId());
189
            }
190
        } elseif ($currentView() instanceof BusinessTemplate && strpos($query, ':currentEntity') !== false) {
191
            $itemsQueryBuilder->setParameter('currentEntity', $containerEntity->getEntity()->getId());
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 getEntity() does only exist in the following implementations of said interface: Victoire\Bundle\WidgetBundle\Entity\Widget, Victoire\Widget\ForceBundle\Entity\WidgetForce, Victoire\Widget\LightSab...Entity\WidgetLightSaber.

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...
192
        }
193
194
        if (strpos($query, ':currentUser') !== false && is_object($this->getCurrentUser())) {
195
            if (is_object($this->getCurrentUser())) {
196
                $itemsQueryBuilder->setParameter('currentUser', $this->getCurrentUser()->getId());
197
            } else {
198
                throw new AccessDeniedException();
199
            }
200
        }
201
202
        return $itemsQueryBuilder;
203
    }
204
205
    /**
206
     * Check if field is a OneToOne, OneToMany, ManyToOne or ManyToMany association.
207
     *
208
     * @param \ReflectionProperty $field
209
     *
210
     * @return bool
211
     */
212
    private function isAssociationField(\ReflectionProperty $field)
213
    {
214
        $annotations = $this->reader->getPropertyAnnotations($field);
215
        foreach ($annotations as $key => $annotationObj) {
216
            if ($annotationObj instanceof OneToOne || $annotationObj instanceof OneToMany || $annotationObj instanceof ManyToOne || $annotationObj instanceof ManyToMany) {
217
                return true;
218
            }
219
        }
220
221
        return false;
222
    }
223
224
    /**
225
     * @return UserInterface|string
226
     */
227
    public function getCurrentUser()
0 ignored issues
show
introduced by
Declare public methods first,then protected ones and finally private ones
Loading history...
228
    {
229
        return $this->tokenStorage->getToken()->getUser();
230
    }
231
}
232