Completed
Pull Request — master (#828)
by
unknown
06:19
created

BusinessEntitySubscriber::updateViewReference()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
rs 8.8571
cc 5
eloc 8
nc 8
nop 1
1
<?php
2
3
namespace Victoire\Bundle\BusinessEntityBundle\EventSubscriber;
4
5
use Doctrine\Common\Collections\ArrayCollection;
6
use Doctrine\Common\EventSubscriber;
7
use Doctrine\ORM\EntityManager;
8
use Doctrine\ORM\Event\LifecycleEventArgs;
9
use Doctrine\ORM\Event\PostFlushEventArgs;
10
use Doctrine\ORM\UnitOfWork;
11
use Knp\DoctrineBehaviors\Model\Translatable\Translation;
12
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
13
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity;
14
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
15
use Victoire\Bundle\BusinessPageBundle\Builder\BusinessPageBuilder;
16
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
17
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
18
use Victoire\Bundle\BusinessPageBundle\Helper\BusinessPageHelper;
19
use Victoire\Bundle\BusinessPageBundle\Repository\BusinessPageRepository;
20
use Victoire\Bundle\ViewReferenceBundle\Event\ViewReferenceEvent;
21
use Victoire\Bundle\ViewReferenceBundle\ViewReferenceEvents;
22
23
class BusinessEntitySubscriber implements EventSubscriber
24
{
25
    protected $businessPageBuilder;
26
    protected $dispatcher;
27
    protected $businessEntityHelper;
28
    protected $flushedBusinessEntities;
29
    protected $businessPageHelper;
30
    protected $flushedBusinessTemplates;
31
32
    /**
33
     * @param BusinessPageBuilder      $businessPageBuilder
34
     * @param BusinessEntityHelper     $businessEntityHelper
35
     * @param BusinessPageHelper       $businessPageHelper
36
     * @param EventDispatcherInterface $dispatcher
37
     */
38
    public function __construct(
39
        BusinessPageBuilder          $businessPageBuilder,
40
        BusinessEntityHelper         $businessEntityHelper,
41
        BusinessPageHelper           $businessPageHelper,
42
        EventDispatcherInterface     $dispatcher
43
    ) {
44
        $this->businessPageBuilder = $businessPageBuilder;
45
        $this->businessEntityHelper = $businessEntityHelper;
46
        $this->businessPageHelper = $businessPageHelper;
47
        $this->dispatcher = $dispatcher;
48
        $this->flushedBusinessEntities = new ArrayCollection();
49
        $this->flushedBusinessTemplates = new ArrayCollection();
50
    }
51
52
    /**
53
     * bind to LoadClassMetadata method.
54
     *
55
     * @return string[] The subscribed events
56
     */
57
    public function getSubscribedEvents()
58
    {
59
        return [
60
            'postUpdate',
61
            'postPersist',
62
            'preRemove',
63
            'postFlush',
64
        ];
65
    }
66
67
    /**
68
     * @param LifecycleEventArgs $eventArgs
69
     */
70
    public function postUpdate(LifecycleEventArgs $eventArgs)
71
    {
72
        /** @var EntityManager $entityManager */
73
        $entityManager = $eventArgs->getEntityManager();
74
        /** @var UnitOfWork $uow */
75
        $uow = $entityManager->getUnitOfWork();
76
77
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
78
            $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $businessEntity is correct as $this->businessEntityHel...EntityInstance($entity) (which targets Victoire\Bundle\Business...:findByEntityInstance()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
79
            if ($businessEntity) {
80
                $this->updateBusinessPages(
81
                    $entity,
82
                    $businessEntity,
83
                    $entityManager,
84
                    $uow->getScheduledEntityDeletions()
85
                );
86
            }
87
        }
88
        $this->updateViewReference($eventArgs);
89
    }
90
91
    /**
92
     * @param LifecycleEventArgs $eventArgs
93
     */
94
    public function postPersist(LifecycleEventArgs $eventArgs)
95
    {
96
        $this->updateViewReference($eventArgs);
97
    }
98
99
    /**
100
     * get BusinessTemplate concerned by this entity (if so)
101
     * then get BusinessPages
102
     * for each BusinessPage, update its slug according to the new slug (if so).
103
     *
104
     * @param $entity
105
     * @param BusinessEntity $businessEntity
106
     * @param EntityManager  $entityManager
107
     * @param array          $deletions
108
     *
109
     * @throws \Exception
110
     *
111
     * @internal param LifecycleEventArgs $eventArgs
112
     */
113
    public function updateBusinessPages($entity, BusinessEntity $businessEntity, EntityManager $entityManager, $deletions)
114
    {
115
        $businessTemplates = $entityManager->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
116
        foreach ($businessTemplates as $businessTemplate) {
117
            // Generate viewRef for each BT translation
118
            /** @var ViewTra $translation */
119
            foreach ($businessTemplate->getTranslations() as $translation) {
120
                $businessTemplate->setCurrentLocale($translation->getLocale());
121
                if ($this->businessPageHelper->isEntityAllowed($businessTemplate, $entity, $entityManager)) {
122
                    /** @var BusinessPageRepository $bepRepo */
123
                    $bepRepo = $entityManager->getRepository('VictoireBusinessPageBundle:BusinessPage');
124
                    $virtualBusinessPage = $this->businessPageBuilder->generateEntityPageFromTemplate(
125
                        $businessTemplate,
126
                        $entity,
127
                        $entityManager
128
                    );
129
                    // Get the BusinessPage if exists for the given entity
130
                    /** @var BusinessPage $businessPage */
131
                    $businessPage = $bepRepo->findPageByBusinessEntityAndPattern(
132
                        $businessTemplate,
133
                        $entity,
134
                        $businessEntity
135
                    );
136
                    $businessPage->setCurrentLocale($translation->getLocale());
137
                    // If there is diff between persisted BEP and computed, persist the change
138
                    $scheduledForRemove = false;
139
                    foreach ($deletions as $deletion) {
140
                        if (get_class($deletion) == get_class($businessPage)
141
                            && $deletion->getId() === $businessPage->getId()
142
                        ) {
143
                            $scheduledForRemove = true;
144
                        }
145
                    }
146
147
                    if ($businessPage && !$scheduledForRemove) {
148
                        $oldSlug = $businessPage->getSlug();
0 ignored issues
show
Unused Code introduced by
$oldSlug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
149
                        $newSlug = $entity->getSlug();
0 ignored issues
show
Unused Code introduced by
$newSlug is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
150
                        $businessPage->setName($virtualBusinessPage->getName());
151
                        $businessPage->setSlug($virtualBusinessPage->getSlug());
152
153
                        $entityManager->persist($businessPage);
154
                        $entityManager->flush();
155
                    }
156
                }
157
            }
158
        }
159
    }
160
161
    /**
162
     * Iterate over inserted BusinessEntities and BusinessTemplates catched by postPersist
163
     * and dispatch event to generate the needed ViewReferences.
164
     *
165
     * @param PostFlushEventArgs $eventArgs
166
     *
167
     * @throws \Exception
168
     */
169
    public function postFlush(PostFlushEventArgs $eventArgs)
170
    {
171
        $em = $eventArgs->getEntityManager();
172 View Code Duplication
        foreach ($this->flushedBusinessEntities as $entity) {
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...
173
            $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
174
            //find all BT that can represent the businessEntity
175
            $businessTemplates = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
176
            foreach ($businessTemplates as $businessTemplate) {
177
                //generate a viewReference for each BT translation
178
                foreach ($businessTemplate->getTranslations() as $translation) {
179
                    $businessTemplate->setCurrentLocale($translation->getLocale());
180
181
                    if ($page = $em->getRepository(
182
                        'Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage'
183
                    )->findPageByBusinessEntityAndPattern($businessTemplate, $entity, $businessEntity)
184
                    ) {
185
                        //if it's a BP we update the BP
186
                        $this->businessPageBuilder->updatePageParametersByEntity($page, $entity);
187
                    } else {
188
                        $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
189
                            $businessTemplate,
190
                            $entity,
191
                            $em
192
                        );
193
                    }
194
                    if ($this->businessPageHelper->isEntityAllowed($businessTemplate, $entity, $em)) {
195
                        //update the reference
196
                        $event = new ViewReferenceEvent($page);
197
                        $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
198
                    }
199
                }
200
            }
201
        }
202
203 View Code Duplication
        foreach ($this->flushedBusinessTemplates as $entity) {
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...
204
            $businessEntityId = $entity->getBusinessEntityId();
205
            $businessEntity = $this->businessEntityHelper->findById($businessEntityId);
206
            //find all entities
207
            $entities = $this->businessPageHelper->getEntitiesAllowed($entity, $em);
208
            //generate a viewReference for each BT translation
209
            foreach ($entity->getTranslations() as $translation) {
210
                $entity->setCurrentLocale($translation->getLocale());
211
                foreach ($entities as $be) {
212
                    if ($this->businessPageHelper->isEntityAllowed($entity, $be, $em)) {
213
                        if ($page = $em->getRepository(
214
                            'Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage'
215
                        )->findPageByBusinessEntityAndPattern($entity, $be, $businessEntity)
216
                        ) {
217
                            //rebuild page if its a BP
218
                            $this->businessPageBuilder->updatePageParametersByEntity($page, $be);
219
                        } else {
220
                            $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
221
                                $entity,
222
                                $be,
223
                                $em
224
                            );
225
                        }
226
                        // update reference
227
                        $event = new ViewReferenceEvent($page);
228
                        $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
229
                    }
230
                }
231
            }
232
        }
233
        $this->flushedBusinessEntities->clear();
234
        $this->flushedBusinessTemplates->clear();
235
    }
236
237
    /**
238
     * This method throw an event if needed for a view related to a businessEntity.
239
     *
240
     * @param LifecycleEventArgs $eventArgs
241
     *
242
     * @throws \Exception
243
     */
244
    private function updateViewReference(LifecycleEventArgs $eventArgs)
245
    {
246
        $entity = $eventArgs->getEntity();
247
248
        //if entity is a translation, get its translatable entity
249
        if (in_array(Translation::class, class_uses($entity)) && null !== $entity->getTranslatable()) {
250
            $entity = $entity->getTranslatable();
251
        }
252
253
        //if it's a businessEntity we need to rebuild virtuals (BPs are rebuild in businessEntitySubscriber)
254
        if ($businessEntity = $this->businessEntityHelper->findByEntityInstance($entity)) {
0 ignored issues
show
Unused Code introduced by
$businessEntity is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
255
            $this->flushedBusinessEntities->add($entity);
256
        }
257
        //if it a businessTemplate we have to rebuild virtuals or update BP
258
        if ($entity instanceof BusinessTemplate) {
259
            $this->flushedBusinessTemplates->add($entity);
260
        }
261
    }
262
263
    /**
264
     * @param LifecycleEventArgs $eventArgs
265
     *
266
     * @throws \Exception
267
     */
268
    public function preRemove(LifecycleEventArgs $eventArgs)
269
    {
270
        $entity = $eventArgs->getEntity();
271
272
        //if we remove a BP we need to replace by a VBP ref
273
        if ($entity instanceof BusinessPage) {
274
            //remove BP ref
275
            $event = new ViewReferenceEvent($entity);
276
            $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
277
            $em = $eventArgs->getEntityManager();
278
            $businessTemplate = $entity->getTemplate();
279
            $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
280
                $businessTemplate,
0 ignored issues
show
Documentation introduced by
$businessTemplate is of type string, but the function expects a object<Victoire\Bundle\B...ntity\BusinessTemplate>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
281
                $entity->getBusinessEntity(),
282
                $em
283
            );
284
            //create VBP ref
285
            //TODO :: dont rebuild if businessEntity or businessTemplate doesn't exist
286
            $event = new ViewReferenceEvent($page);
287
            $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
288
        }
289
290
        //if it's a businessEntity, we need to remove all BP and VBP ref
291
        if ($businessEntity = $this->businessEntityHelper->findByEntityInstance($entity)) {
292
            $em = $eventArgs->getEntityManager();
293
            $businessTemplates = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
294
            foreach ($businessTemplates as $businessTemplate) {
295
296
                //generate a viewReference for each BT translation
297
                foreach ($businessTemplate->getTranslations() as $translation) {
298
                    $businessTemplate->setCurrentLocale($translation->getLocale());
299
                    if ($page = $em->getRepository('Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage')->findPageByBusinessEntityAndPattern($businessTemplate, $entity, $businessEntity)) {
300
                        $event = new ViewReferenceEvent($page);
301
                        $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
302
                    } else {
303
                        $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
304
                            $businessTemplate,
305
                            $entity,
306
                            $em
307
                        );
308
                        $event = new ViewReferenceEvent($page);
309
                        $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
310
                    }
311
                }
312
            }
313
        }
314
        //if we remove a businessTemplate remove all VBT ref (BP cascade remove)
315
        if ($entity instanceof BusinessTemplate) {
316
            $em = $eventArgs->getEntityManager();
317
            $entities = $this->businessPageHelper->getEntitiesAllowed($entity, $em);
318
319
            //generate a viewReference for each BT translation
320
            foreach ($entity->getTranslations() as $translation) {
321
                $entity->setCurrentLocale($translation->getLocale());
322
                foreach ($entities as $be) {
323
                    $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
324
                        $entity,
325
                        $be,
326
                        $em
327
                    );
328
                    $event = new ViewReferenceEvent($page);
329
                    $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
330
                }
331
            }
332
        }
333
    }
334
}
335