Completed
Pull Request — master (#351)
by Leny
06:37
created

QueryHelper::checkObjectHasQueryTrait()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 11
rs 9.2
cc 4
eloc 5
nc 3
nop 1
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\QueryBuilder;
12
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
13
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
14
use Victoire\Bundle\CoreBundle\Helper\CurrentViewHelper;
15
use Victoire\Bundle\QueryBundle\Entity\VictoireQueryInterface;
16
17
/**
18
 * The QueryHelper helps to build query in Victoire's components
19
 * ref: victoire_query.query_helper.
20
 */
21
class QueryHelper
22
{
23
    protected $businessEntityHelper = null;
24
    protected $currentView;
25
    protected $reader;
26
27
    /**
28
     * Constructor.
29
     *
30
     * @param BusinessEntityHelper $businessEntityHelper
31
     * @param CurrentViewHelper    $currentView
32
     * @param Reader               $reader
33
     */
34
    public function __construct(BusinessEntityHelper $businessEntityHelper, CurrentViewHelper $currentView, Reader $reader)
35
    {
36
        $this->businessEntityHelper = $businessEntityHelper;
37
        $this->currentView = $currentView;
38
        $this->reader = $reader;
39
    }
40
41
    /**
42
     * Get the query builder base. This makes a "select  from item XXX"
43
     * use the item for doing the left join or where dql.
44
     *
45
     * @param \Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate $containerEntity
46
     *
47
     * @throws Exception
48
     *
49
     * @return QueryBuilder
50
     */
51
    public function getQueryBuilder(VictoireQueryInterface $containerEntity, EntityManager $em)
52
    {
53
        if ($containerEntity === null) {
54
            throw new \Exception('The container entity parameter must not be null.');
55
        }
56
57
        //the business name of the container entity
58
        $businessEntityId = $containerEntity->getBusinessEntityId();
59
60
        //test that there is a business entity name
61
        if ($businessEntityId === null || $businessEntityId === '') {
62
            $containerId = $containerEntity->getId();
63
            throw new \Exception('The container entity ['.$containerId.'] does not have any businessEntityId.');
64
        }
65
66
        //the business class of the container entity
67
        $businessEntity = $this->businessEntityHelper->findById(strtolower($businessEntityId));
68
69
        //test that there was a businessEntity
70
        if ($businessEntity === null) {
71
            throw new \Exception('The business entity was not found for the id:['.$businessEntityId.']');
72
        }
73
74
        $businessClass = $businessEntity->getClass();
75
76
        $itemsQueryBuilder = $em
77
            ->createQueryBuilder()
78
            ->select('main_item')
79
            ->from($businessClass, 'main_item');
80
81
        $refClass = new $businessClass();
82
        if (method_exists($refClass, 'getDeletedAt')) {
83
            $itemsQueryBuilder->where('main_item.deletedAt IS NULL');
84
        }
85
86
        return $itemsQueryBuilder;
87
    }
88
89
    /**
90
     * Get the results from the sql after adding the.
91
     *
92
     * @param VictoireQueryInterface $containerEntity
93
     * @param QueryBuilder           $itemsQueryBuilder
94
     *
95
     * @throws \Exception
96
     *
97
     * @return QueryBuilder The QB to list of objects
98
     */
99
    public function buildWithSubQuery(VictoireQueryInterface $containerEntity, QueryBuilder $itemsQueryBuilder, EntityManager $em)
100
    {
101
        //get the query of the container entity
102
        $query = $containerEntity->getQuery();
103
        if (method_exists($containerEntity, 'additionnalQueryPart')) {
104
            $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...
105
        }
106
107
        if ($query !== '' && $query !== null) {
108
            $subQuery = $em->createQueryBuilder()
109
                                ->select('item.id')
110
                                ->from($itemsQueryBuilder->getRootEntities()[0], 'item');
111
112
            $itemsQueryBuilder->andWhere(
113
                sprintf('main_item.id IN (%s %s)', $subQuery->getQuery()->getDql(), $query)
114
            );
115
        }
116
117
        //Add ORDER BY if set
118
        if ($orderBy = json_decode($containerEntity->getOrderBy(), true)) {
119
            foreach ($orderBy as $addOrderBy) {
120
                $reflectionClass = new \ReflectionClass($itemsQueryBuilder->getRootEntities()[0]);
121
                $reflectionProperty = $reflectionClass->getProperty($addOrderBy['by']);
122
123
                //If ordering field is an association, treat it as a boolean
124
                if ($this->isAssociationField($reflectionProperty)) {
125
                    $itemsQueryBuilder->addSelect('CASE WHEN main_item.'.$addOrderBy['by'].' IS NULL THEN 0 ELSE 1 END AS HIDDEN caseOrder');
126
                    $itemsQueryBuilder->addOrderBy('caseOrder', $addOrderBy['order']);
127
                } else {
128
                    $itemsQueryBuilder->addOrderBy('main_item.'.$addOrderBy['by'], $addOrderBy['order']);
129
                }
130
            }
131
        }
132
133
        $currentView = $this->currentView;
134
135
        // If the current page is a BEP, we parse all its properties and inject them as query parameters
136
        if ($currentView() && $currentView() instanceof BusinessPage && null !== $currentEntity = $currentView()->getBusinessEntity()) {
137
138
            // NEW
139
            $metadatas = $em->getClassMetadata(get_class($currentEntity));
140 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...
141
                if (strpos($query, ':'.$fieldName) !== false) {
142
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName));
143
                }
144
            }
145 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...
146
                if (strpos($query, ':'.$fieldName) !== false) {
147
                    $itemsQueryBuilder->setParameter($fieldName, $metadatas->getFieldValue($currentEntity, $fieldName)->getId());
148
                }
149
            }
150
151
            if (strpos($query, ':currentEntity') !== false) {
152
                $itemsQueryBuilder->setParameter('currentEntity', $currentEntity->getId());
153
            }
154
        }
155
156
        return $itemsQueryBuilder;
157
    }
158
159
    /**
160
     * Check if field is a OneToOne, OneToMany, ManyToOne or ManyToMany association.
161
     *
162
     * @param \ReflectionProperty $field
163
     *
164
     * @return bool
165
     */
166
    private function isAssociationField(\ReflectionProperty $field)
167
    {
168
        $annotations = $this->reader->getPropertyAnnotations($field);
169
        foreach ($annotations as $key => $annotationObj) {
170
            if ($annotationObj instanceof OneToOne || $annotationObj instanceof OneToMany || $annotationObj instanceof ManyToOne || $annotationObj instanceof ManyToMany) {
171
                return true;
172
            }
173
        }
174
175
        return false;
176
    }
177
}
178