BusinessEntitySubscriber   B
last analyzed

Complexity

Total Complexity 40

Size/Duplication

Total Lines 311
Duplicated Lines 24.44 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 40
lcom 1
cbo 15
dl 76
loc 311
rs 7.6556
c 1
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
B updateViewReference() 0 18 5
A __construct() 0 13 1
A getSubscribedEvents() 0 9 1
A postUpdate() 0 20 3
A postPersist() 0 4 1
D updateBusinessPages() 0 45 9
C postFlush() 48 68 11
C preRemove() 28 66 9

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like BusinessEntitySubscriber often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BusinessEntitySubscriber, and based on these observations, apply Extract Interface, too.

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\I18nBundle\Entity\ViewTranslation;
21
use Victoire\Bundle\ViewReferenceBundle\Event\ViewReferenceEvent;
22
use Victoire\Bundle\ViewReferenceBundle\ViewReferenceEvents;
23
24
class BusinessEntitySubscriber implements EventSubscriber
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
25
{
26
    protected $businessPageBuilder;
27
    protected $dispatcher;
28
    protected $businessEntityHelper;
29
    protected $flushedBusinessEntities;
30
    protected $businessPageHelper;
31
    protected $flushedBusinessTemplates;
32
33
    /**
34
     * @param BusinessPageBuilder      $businessPageBuilder
35
     * @param BusinessEntityHelper     $businessEntityHelper
36
     * @param BusinessPageHelper       $businessPageHelper
37
     * @param EventDispatcherInterface $dispatcher
38
     */
39
    public function __construct(
40
        BusinessPageBuilder          $businessPageBuilder,
41
        BusinessEntityHelper         $businessEntityHelper,
42
        BusinessPageHelper           $businessPageHelper,
43
        EventDispatcherInterface     $dispatcher
44
    ) {
45
        $this->businessPageBuilder = $businessPageBuilder;
46
        $this->businessEntityHelper = $businessEntityHelper;
47
        $this->businessPageHelper = $businessPageHelper;
48
        $this->dispatcher = $dispatcher;
49
        $this->flushedBusinessEntities = new ArrayCollection();
50
        $this->flushedBusinessTemplates = new ArrayCollection();
51
    }
52
53
    /**
54
     * bind to LoadClassMetadata method.
55
     *
56
     * @return string[] The subscribed events
57
     */
58
    public function getSubscribedEvents()
59
    {
60
        return [
61
            'postUpdate',
62
            'postPersist',
63
            'preRemove',
64
            'postFlush',
65
        ];
66
    }
67
68
    /**
69
     * @param LifecycleEventArgs $eventArgs
70
     */
71
    public function postUpdate(LifecycleEventArgs $eventArgs)
72
    {
73
        /** @var EntityManager $entityManager */
74
        $entityManager = $eventArgs->getEntityManager();
75
        /** @var UnitOfWork $uow */
76
        $uow = $entityManager->getUnitOfWork();
77
78
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
79
            $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...
80
            if ($businessEntity) {
81
                $this->updateBusinessPages(
82
                    $entity,
83
                    $businessEntity,
84
                    $entityManager,
85
                    $uow->getScheduledEntityDeletions()
86
                );
87
            }
88
        }
89
        $this->updateViewReference($eventArgs);
90
    }
91
92
    /**
93
     * @param LifecycleEventArgs $eventArgs
94
     */
95
    public function postPersist(LifecycleEventArgs $eventArgs)
96
    {
97
        $this->updateViewReference($eventArgs);
98
    }
99
100
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$entity" missing
Loading history...
101
     * get BusinessTemplate concerned by this entity (if so)
102
     * then get BusinessPages
103
     * for each BusinessPage, update its slug according to the new slug (if so).
104
     *
105
     * @param $entity
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
106
     * @param BusinessEntity $businessEntity
107
     * @param EntityManager  $entityManager
108
     * @param array          $deletions
109
     *
110
     * @throws \Exception
111
     *
112
     * @internal param LifecycleEventArgs $eventArgs
113
     */
114
    public function updateBusinessPages($entity, BusinessEntity $businessEntity, EntityManager $entityManager, $deletions)
115
    {
116
        $businessTemplates = $entityManager->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
117
        foreach ($businessTemplates as $businessTemplate) {
118
            // Generate a viewReference for each BT translation
119
            /** @var ViewTranslation $translation */
120
            foreach ($businessTemplate->getTranslations() as $translation) {
121
                $businessTemplate->setCurrentLocale($translation->getLocale());
122
                if ($this->businessPageHelper->isEntityAllowed($businessTemplate, $entity, $entityManager)) {
123
                    /** @var BusinessPageRepository $bepRepo */
124
                    $bepRepo = $entityManager->getRepository('VictoireBusinessPageBundle:BusinessPage');
125
                    $virtualBusinessPage = $this->businessPageBuilder->generateEntityPageFromTemplate(
126
                        $businessTemplate,
127
                        $entity,
128
                        $entityManager
129
                    );
130
                    // Get the BusinessPage if exists for the given entity
131
                    /** @var BusinessPage $businessPage */
132
                    $businessPage = $bepRepo->findPageByBusinessEntityAndPattern(
133
                        $businessTemplate,
134
                        $entity,
135
                        $businessEntity
136
                    );
137
                    $businessPage->setCurrentLocale($translation->getLocale());
138
                    // If there is diff between persisted BEP and computed, persist the change
139
                    $scheduledForRemove = false;
140
                    foreach ($deletions as $deletion) {
141
                        if (get_class($deletion) == get_class($businessPage)
142
                            && $deletion->getId() === $businessPage->getId()
143
                        ) {
144
                            $scheduledForRemove = true;
145
                        }
146
                    }
147
148
                    if ($businessPage && !$scheduledForRemove) {
149
                        $businessPage->setName($virtualBusinessPage->getName());
150
                        $businessPage->setSlug($virtualBusinessPage->getSlug());
151
152
                        $entityManager->persist($businessPage);
153
                    }
154
                }
155
            }
156
        }
157
        $entityManager->flush();
158
    }
159
160
    /**
161
     * Iterate over inserted BusinessEntities and BusinessTemplates catched by postPersist
162
     * and dispatch event to generate the needed ViewReferences.
163
     *
164
     * @param PostFlushEventArgs $eventArgs
165
     *
166
     * @throws \Exception
167
     */
168
    public function postFlush(PostFlushEventArgs $eventArgs)
169
    {
170
        $em = $eventArgs->getEntityManager();
171
        foreach ($this->flushedBusinessEntities as $entity) {
172
            $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
173
            //find all BT that can represent the businessEntity
174
            $businessTemplates = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
175 View Code Duplication
            foreach ($businessTemplates as $businessTemplate) {
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...
176
                // Generate a viewReference for each BT translation
177
                foreach ($businessTemplate->getTranslations() as $translation) {
178
                    $businessTemplate->setCurrentLocale($translation->getLocale());
179
180
                    if ($page = $em->getRepository(
181
                        'Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage'
182
                    )->findPageByBusinessEntityAndPattern($businessTemplate, $entity, $businessEntity)
183
                    ) {
184
                        //if it's a BP we update the BP
185
                        $this->businessPageBuilder->updatePageParametersByEntity($page, $entity);
186
                    } else {
187
                        $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
188
                            $businessTemplate,
189
                            $entity,
190
                            $em
191
                        );
192
                    }
193
                    if ($this->businessPageHelper->isEntityAllowed($businessTemplate, $entity, $em)) {
194
                        //update the reference
195
                        $event = new ViewReferenceEvent($page);
196
                        $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
197
                    }
198
                }
199
            }
200
        }
201
202
        foreach ($this->flushedBusinessTemplates as $entity) {
203
            $em = $eventArgs->getEntityManager();
204
            $businessEntityId = $entity->getBusinessEntityName();
205
            $businessEntity = $eventArgs->getEntityManager()->getRepository('VictoireBusinessEntityBundle:BusinessEntity')->findOneBy(['name' => $businessEntityId]);
206
            //find all entities
207
            $entities = $this->businessPageHelper->getEntitiesAllowed($entity, $em);
208
            // Generate a viewReference for each BT translation
209 View Code Duplication
            foreach ($entity->getTranslations() as $translation) {
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...
210
                $entity->setCurrentLocale($translation->getLocale());
211
                foreach ($entities as $be) {
0 ignored issues
show
Bug introduced by
The expression $entities of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
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)
0 ignored issues
show
introduced by
Declare public methods first,then protected ones and finally private ones
Loading history...
269
    {
270
        $entity = $eventArgs->getEntity();
271
272
        //if we remove a BP we need to replace by a VBP ref
273 View Code Duplication
        if ($entity instanceof BusinessPage) {
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...
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->getEntity(),
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) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
295
296
                // Generate a viewReference for each BT translation
297
                foreach ($businessTemplate->getTranslations() as $translation) {
298
                    $businessTemplate->setCurrentLocale($translation->getLocale());
299 View Code Duplication
                    if ($page = $em->getRepository('Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage')->findPageByBusinessEntityAndPattern($businessTemplate, $entity, $businessEntity)) {
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...
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) {
0 ignored issues
show
Bug introduced by
The expression $entities of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
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