Completed
Push — master ( c22408...290846 )
by Leny
11:32 queued 05:38
created

QueryHelper::getCurrentUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

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