Completed
Push — master ( 9745cb...81e988 )
by Paul
06:43
created

BusinessEntitySubscriber   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 259
Duplicated Lines 15.44 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 31
lcom 1
cbo 10
dl 40
loc 259
rs 9.8
c 1
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
C updateBusinessPages() 0 48 9
A __construct() 0 10 1
A getSubscribedEvents() 0 8 1
A postUpdate() 0 20 3
A postPersist() 0 4 1
C updateViewReference() 40 58 9
B preRemove() 0 56 7

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\BusinessEntityBundle\EventSubscriber;
4
5
use Doctrine\Common\EventSubscriber;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\Event\LifecycleEventArgs;
8
use Doctrine\ORM\UnitOfWork;
9
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
10
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity;
11
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
12
use Victoire\Bundle\BusinessPageBundle\Builder\BusinessPageBuilder;
13
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
14
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
15
use Victoire\Bundle\BusinessPageBundle\Helper\BusinessPageHelper;
16
use Victoire\Bundle\BusinessPageBundle\Repository\BusinessPageRepository;
17
use Victoire\Bundle\ViewReferenceBundle\Event\ViewReferenceEvent;
18
use Victoire\Bundle\ViewReferenceBundle\ViewReferenceEvents;
19
20
class BusinessEntitySubscriber implements EventSubscriber
21
{
22
    protected $businessPageBuilder;
23
    protected $dispatcher;
24
25
    /**
26
     * @param BusinessPageBuilder      $businessPageBuilder
27
     * @param BusinessEntityHelper     $businessEntityHelper
28
     * @param BusinessPageHelper       $businessPageHelper
29
     * @param EventDispatcherInterface $dispatcher
30
     */
31
    public function __construct(BusinessPageBuilder          $businessPageBuilder,
32
                                BusinessEntityHelper         $businessEntityHelper,
33
                                BusinessPageHelper           $businessPageHelper,
34
                                EventDispatcherInterface     $dispatcher
35
    ) {
36
        $this->businessPageBuilder = $businessPageBuilder;
37
        $this->businessEntityHelper = $businessEntityHelper;
0 ignored issues
show
Bug introduced by
The property businessEntityHelper does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
38
        $this->businessPageHelper = $businessPageHelper;
0 ignored issues
show
Bug introduced by
The property businessPageHelper does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
39
        $this->dispatcher = $dispatcher;
40
    }
41
42
    /**
43
     * bind to LoadClassMetadata method.
44
     *
45
     * @return string[] The subscribed events
46
     */
47
    public function getSubscribedEvents()
48
    {
49
        return [
50
            'postUpdate',
51
            'postPersist',
52
            'preRemove',
53
        ];
54
    }
55
56
    /**
57
     * @param LifecycleEventArgs $eventArgs
58
     */
59
    public function postUpdate(LifecycleEventArgs $eventArgs)
60
    {
61
        /** @var EntityManager $entityManager */
62
        $entityManager = $eventArgs->getEntityManager();
63
        /** @var UnitOfWork $uow */
64
        $uow = $entityManager->getUnitOfWork();
65
66
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
67
            $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
68
            if ($businessEntity) {
69
                $this->updateBusinessPages(
70
                    $entity,
71
                    $businessEntity,
72
                    $entityManager,
73
                    $uow->getScheduledEntityDeletions()
74
                );
75
            }
76
        }
77
        $this->updateViewReference($eventArgs);
78
    }
79
80
    /**
81
     * @param LifecycleEventArgs $eventArgs
82
     */
83
    public function postPersist(LifecycleEventArgs $eventArgs)
84
    {
85
        $this->updateViewReference($eventArgs);
86
    }
87
88
    /**
89
     * get BusinessTemplate concerned by this entity (if so)
90
     * then get BusinessPages
91
     * for each BusinessPage, update its slug according to the new slug (if so).
92
     *
93
     * @param $entity
94
     * @param BusinessEntity $businessEntity
95
     * @param EntityManager  $entityManager
96
     * @param array          $deletions
97
     *
98
     * @throws \Exception
99
     *
100
     * @internal param LifecycleEventArgs $eventArgs
101
     */
102
    public function updateBusinessPages($entity, BusinessEntity $businessEntity, EntityManager $entityManager, $deletions)
103
    {
104
        $businessTemplates = $entityManager->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
105
        foreach ($businessTemplates as $businessTemplate) {
106
            if ($this->businessPageHelper->isEntityAllowed($businessTemplate, $entity, $entityManager)) {
107
                /** @var BusinessPageRepository $bepRepo */
108
                $bepRepo = $entityManager->getRepository('VictoireBusinessPageBundle:BusinessPage');
109
                $virtualBusinessPage = $this->businessPageBuilder->generateEntityPageFromTemplate(
110
                    $businessTemplate,
111
                    $entity,
112
                    $entityManager
113
                );
114
                // Get the BusinessPage if exists for the given entity
115
                /** @var BusinessPage $businessPage */
116
                $businessPage = $bepRepo->findPageByBusinessEntityAndPattern(
117
                    $businessTemplate,
118
                    $entity,
119
                    $businessEntity
120
                );
121
                // If there is diff between persisted BEP and computed, persist the change
122
                $scheduledForRemove = false;
123
                foreach ($deletions as $deletion) {
124
                    if (get_class($deletion) == get_class($businessPage)
125
                        && $deletion->getId() === $businessPage->getId()
126
                    ) {
127
                        $scheduledForRemove = true;
128
                    }
129
                }
130
131
                if ($businessPage && !$scheduledForRemove) {
132
                    $oldSlug = $businessPage->getSlug();
133
                    $newSlug = $entity->getSlug();
134
                    $staticUrl = $businessPage->getStaticUrl();
135
136
                    if ($staticUrl) {
137
                        $staticUrl = preg_replace('/'.$oldSlug.'/', $newSlug, $staticUrl);
138
                        $businessPage->setStaticUrl($staticUrl);
0 ignored issues
show
Bug introduced by
It seems like $staticUrl defined by preg_replace('/' . $oldS..., $newSlug, $staticUrl) on line 137 can also be of type array<integer,string>; however, Victoire\Bundle\Business...essPage::setStaticUrl() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
139
                    }
140
141
                    $businessPage->setName($virtualBusinessPage->getName());
142
                    $businessPage->setSlug($virtualBusinessPage->getSlug());
143
144
                    $entityManager->persist($businessPage);
145
                    $entityManager->flush();
146
                }
147
            }
148
        }
149
    }
150
151
    /**
152
     * This method throw an event if needed for a view related to a businessEntity.
153
     *
154
     * @param LifecycleEventArgs $eventArgs
155
     *
156
     * @throws \Exception
157
     */
158
    private function updateViewReference(LifecycleEventArgs $eventArgs)
159
    {
160
        $entity = $eventArgs->getEntity();
161
        //if it's a businessEntity we need to rebuild virtuals (BPs are rebuild in businessEntitySubscriber)
162
        if ($businessEntity = $this->businessEntityHelper->findByEntityInstance($entity)) {
163
            $em = $eventArgs->getEntityManager();
164
            //find all BT that can represent the businessEntity
165
            $businessTemplates = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
166 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...
167
                if ($page = $em->getRepository(
168
                    'Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage'
169
                )->findPageByBusinessEntityAndPattern($businessTemplate, $entity, $businessEntity)
170
                ) {
171
                    //if it's a BP we update the BP
172
                    $this->businessPageBuilder->updatePageParametersByEntity($page, $entity);
173
                } else {
174
                    $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
175
                        $businessTemplate,
176
                        $entity,
177
                        $em
178
                    );
179
                }
180
                if ($this->businessPageHelper->isEntityAllowed($businessTemplate, $entity, $em)) {
181
                    //update the reference
182
                    $event = new ViewReferenceEvent($page);
183
                    $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
184
                }
185
            }
186
        }
187
        //if it a businessTemplate we have to rebuild virtuals or update BP
188
        if ($entity instanceof BusinessTemplate) {
189
            $em = $eventArgs->getEntityManager();
190
            $businessEntityId = $entity->getBusinessEntityId();
191
            $businessEntity = $this->businessEntityHelper->findById($businessEntityId);
192
            //find all entities
193
            $entities = $this->businessPageHelper->getEntitiesAllowed($entity, $em);
194 View Code Duplication
            foreach ($entities as $be) {
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...
195
                if ($this->businessPageHelper->isEntityAllowed($entity, $be, $em)) {
196
                    if ($page = $em->getRepository(
197
                        'Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage'
198
                    )->findPageByBusinessEntityAndPattern($entity, $be, $businessEntity)
199
                    ) {
200
                        //rebuild page if its a BP
201
                        $this->businessPageBuilder->updatePageParametersByEntity($page, $be);
202
                    } else {
203
                        $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
204
                            $entity,
205
                            $be,
206
                            $em
207
                        );
208
                    }
209
                    // update reference
210
                    $event = new ViewReferenceEvent($page);
211
                    $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
212
                }
213
            }
214
        }
215
    }
216
217
    /**
218
     * @param LifecycleEventArgs $eventArgs
219
     *
220
     * @throws \Exception
221
     */
222
    public function preRemove(LifecycleEventArgs $eventArgs)
223
    {
224
        $entity = $eventArgs->getEntity();
225
226
        //if we remove a BP we need to remplace by a VBP ref
227
        if ($entity instanceof BusinessPage) {
228
            //remove BP ref
229
            $event = new ViewReferenceEvent($entity);
230
            $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
231
            $em = $eventArgs->getEntityManager();
232
            $businessTemplate = $entity->getTemplate();
233
            $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
234
                $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...
235
                $entity->getBusinessEntity(),
236
                $em
237
            );
238
            //create VBP ref
239
            //TODO :: dont rebuild if businessEntity or businessTemplate doesn't exist
240
            $event = new ViewReferenceEvent($page);
241
            $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
242
        }
243
244
        //if it's a businessEntity, we need to remove all BP and VBP ref
245
        if ($businessEntity = $this->businessEntityHelper->findByEntityInstance($entity)) {
246
            $em = $eventArgs->getEntityManager();
247
            $businessTemplates = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
248
            foreach ($businessTemplates as $businessTemplate) {
249
                if ($page = $em->getRepository('Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage')->findPageByBusinessEntityAndPattern($businessTemplate, $entity, $businessEntity)) {
250
                    $event = new ViewReferenceEvent($page);
251
                    $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
252
                } else {
253
                    $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
254
                        $businessTemplate,
255
                        $entity,
256
                        $em
257
                    );
258
                    $event = new ViewReferenceEvent($page);
259
                    $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
260
                }
261
            }
262
        }
263
        //if we remove a businessTemplate remove all VBT ref (BP cascade remove)
264
        if ($entity instanceof BusinessTemplate) {
265
            $em = $eventArgs->getEntityManager();
266
            $entities = $this->businessPageHelper->getEntitiesAllowed($entity, $em);
267
            foreach ($entities as $be) {
268
                $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
269
                    $entity,
270
                    $be,
271
                    $em
272
                );
273
                $event = new ViewReferenceEvent($page);
274
                $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
275
            }
276
        }
277
    }
278
}
279