Completed
Push — master ( 7a257e...017c35 )
by Leny
109:58 queued 102:36
created

BusinessEntitySubscriber::preRemove()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 56
Code Lines 37

Duplication

Lines 24
Ratio 42.86 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 24
loc 56
rs 7.749
cc 7
eloc 37
nc 12
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 $viewCacheManager;
23
    protected $viewCacheDriver;
24
    protected $businessPageBuilder;
25
    protected $dispatcher;
26
27
    /**
28
     * @param BusinessPageBuilder      $businessPageBuilder
29
     * @param BusinessEntityHelper     $businessEntityHelper
30
     * @param BusinessPageHelper       $businessPageHelper
31
     * @param EventDispatcherInterface $dispatcher
32
     */
33
    public function __construct(BusinessPageBuilder          $businessPageBuilder,
34
                                BusinessEntityHelper         $businessEntityHelper,
35
                                BusinessPageHelper           $businessPageHelper,
36
                                EventDispatcherInterface     $dispatcher
37
    ) {
38
        $this->businessPageBuilder = $businessPageBuilder;
39
        $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...
40
        $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...
41
        $this->dispatcher = $dispatcher;
42
    }
43
44
    /**
45
     * bind to LoadClassMetadata method.
46
     *
47
     * @return string[] The subscribed events
48
     */
49
    public function getSubscribedEvents()
50
    {
51
        return [
52
            'postUpdate',
53
            'postPersist',
54
            'preRemove',
55
        ];
56
    }
57
58
    /**
59
     * @param LifecycleEventArgs $eventArgs
60
     */
61
    public function postUpdate(LifecycleEventArgs $eventArgs)
62
    {
63
        /** @var EntityManager $entityManager */
64
        $entityManager = $eventArgs->getEntityManager();
65
        /** @var UnitOfWork $uow */
66
        $uow = $entityManager->getUnitOfWork();
67
68
        foreach ($uow->getScheduledEntityInsertions() as $entity) {
69
            $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
70
            if ($businessEntity) {
71
                $this->updateBusinessPages(
72
                    $entity,
73
                    $businessEntity,
74
                    $entityManager,
75
                    $uow->getScheduledEntityDeletions()
76
                );
77
            }
78
        }
79
        $this->updateViewReference($eventArgs);
80
    }
81
82
    /**
83
     * @param LifecycleEventArgs $eventArgs
84
     */
85
    public function postPersist(LifecycleEventArgs $eventArgs)
86
    {
87
        $this->updateViewReference($eventArgs);
88
    }
89
90
    /**
91
     * get BusinessTemplate concerned by this entity (if so)
92
     * then get BusinessPages
93
     * for each BusinessPage, update its slug according to the new slug (if so).
94
     *
95
     * @param $entity
96
     * @param BusinessEntity $businessEntity
97
     * @param EntityManager  $entityManager
98
     * @param array          $deletions
99
     *
100
     * @throws \Exception
101
     *
102
     * @internal param LifecycleEventArgs $eventArgs
103
     */
104
    public function updateBusinessPages($entity, BusinessEntity $businessEntity, EntityManager $entityManager, $deletions)
105
    {
106
        $businessTemplates = $entityManager->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
107
        foreach ($businessTemplates as $businessTemplate) {
108
            if ($this->businessPageHelper->isEntityAllowed($businessTemplate, $entity, $entityManager)) {
109
                /** @var BusinessPageRepository $bepRepo */
110
                $bepRepo = $entityManager->getRepository('VictoireBusinessPageBundle:BusinessPage');
111
                $virtualBusinessPage = $this->businessPageBuilder->generateEntityPageFromTemplate(
112
                    $businessTemplate,
113
                    $entity,
114
                    $entityManager
115
                );
116
                // Get the BusinessPage if exists for the given entity
117
                /** @var BusinessPage $businessPage */
118
                $businessPage = $bepRepo->findPageByBusinessEntityAndPattern(
119
                    $businessTemplate,
120
                    $entity,
121
                    $businessEntity
122
                );
123
                // If there is diff between persisted BEP and computed, persist the change
124
                $scheduledForRemove = false;
125
                foreach ($deletions as $deletion) {
126
                    if (get_class($deletion) == get_class($businessPage)
127
                        && $deletion->getId() === $businessPage->getId()
128
                    ) {
129
                        $scheduledForRemove = true;
130
                    }
131
                }
132
133
                if ($businessPage && !$scheduledForRemove) {
134
                    $oldSlug = $businessPage->getSlug();
135
                    $newSlug = $entity->getSlug();
136
                    $staticUrl = $businessPage->getStaticUrl();
137
138
                    if ($staticUrl) {
139
                        $staticUrl = preg_replace('/'.$oldSlug.'/', $newSlug, $staticUrl);
140
                        $businessPage->setStaticUrl($staticUrl);
0 ignored issues
show
Bug introduced by
It seems like $staticUrl defined by preg_replace('/' . $oldS..., $newSlug, $staticUrl) on line 139 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...
141
                    }
142
143
                    $businessPage->setName($virtualBusinessPage->getName());
144
                    $businessPage->setSlug($virtualBusinessPage->getSlug());
145
146
                    $entityManager->persist($businessPage);
147
                    $entityManager->flush();
148
                }
149
            }
150
        }
151
    }
152
153
    /**
154
     * This method throw an event if needed for a view related to a businessEntity.
155
     *
156
     * @param LifecycleEventArgs $eventArgs
157
     *
158
     * @throws \Exception
159
     */
160
    private function updateViewReference(LifecycleEventArgs $eventArgs)
161
    {
162
        $entity = $eventArgs->getEntity();
163
        //if it's a businessEntity we need to rebuild virtuals (BPs are rebuild in businessEntitySubscriber)
164 View Code Duplication
        if ($businessEntity = $this->businessEntityHelper->findByEntityInstance($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...
165
            $em = $eventArgs->getEntityManager();
166
            //find all BT that can represent the businessEntity
167
            $businessTemplates = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
168
            foreach ($businessTemplates as $businessTemplate) {
169
                if ($page = $em->getRepository('Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage')->findPageByBusinessEntityAndPattern($businessTemplate, $entity, $businessEntity)) {
170
                    //if it's a BP we update the BP
171
                    $this->businessPageBuilder->updatePageParametersByEntity($page, $entity);
172
                } else {
173
                    $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
174
                        $businessTemplate,
175
                        $entity,
176
                        $em
177
                    );
178
                }
179
                //update the reference
180
                $event = new ViewReferenceEvent($page);
181
                $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
182
            }
183
        }
184
        //if it a businessTemplate we have to rebuild virtuals or update BP
185
        if ($entity instanceof BusinessTemplate) {
186
            $em = $eventArgs->getEntityManager();
187
            $businessEntityId = $entity->getBusinessEntityId();
188
            $businessEntity = $this->businessEntityHelper->findById($businessEntityId);
189
            //find all entities
190
            $entities = $this->businessPageHelper->getEntitiesAllowed($entity, $em);
191
            foreach ($entities as $be) {
192
                if ($page = $em->getRepository('Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage')->findPageByBusinessEntityAndPattern($entity, $be, $businessEntity)) {
193
                    //rebuild page if its a BP
194
                    $this->businessPageBuilder->updatePageParametersByEntity($page, $be);
195
                } else {
196
                    $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
197
                        $entity,
198
                        $be,
199
                        $em
200
                    );
201
                }
202
                // update reference
203
                $event = new ViewReferenceEvent($page);
204
                $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
205
            }
206
        }
207
    }
208
209
    /**
210
     * @param LifecycleEventArgs $eventArgs
211
     *
212
     * @throws \Exception
213
     */
214
    public function preRemove(LifecycleEventArgs $eventArgs)
215
    {
216
        $entity = $eventArgs->getEntity();
217
218
        //if we remove a BP we need to remplace by a VBP ref
219
        if ($entity instanceof BusinessPage) {
220
            //remove BP ref
221
            $event = new ViewReferenceEvent($entity);
222
            $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
223
            $em = $eventArgs->getEntityManager();
224
            $businessTemplate = $entity->getTemplate();
225
            $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
226
                $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...
227
                $entity->getBusinessEntity(),
228
                $em
229
            );
230
            //create VBP ref
231
            //TODO :: dont rebuild if businessEntity or businessTemplate doesn't exist
232
            $event = new ViewReferenceEvent($page);
233
            $this->dispatcher->dispatch(ViewReferenceEvents::UPDATE_VIEW_REFERENCE, $event);
234
        }
235
236
        //if it's a businessEntity, we need to remove all BP and VBP ref
237 View Code Duplication
        if ($businessEntity = $this->businessEntityHelper->findByEntityInstance($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...
238
            $em = $eventArgs->getEntityManager();
239
            $businessTemplates = $em->getRepository('VictoireBusinessPageBundle:BusinessTemplate')->findPagePatternByBusinessEntity($businessEntity);
240
            foreach ($businessTemplates as $businessTemplate) {
241
                if ($page = $em->getRepository('Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage')->findPageByBusinessEntityAndPattern($businessTemplate, $entity, $businessEntity)) {
242
                    $event = new ViewReferenceEvent($page);
243
                    $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
244
                } else {
245
                    $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
246
                        $businessTemplate,
247
                        $entity,
248
                        $em
249
                    );
250
                    $event = new ViewReferenceEvent($page);
251
                    $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
252
                }
253
            }
254
        }
255
        //if we remove a businessTemplate remove all VBT ref (BP cascade remove)
256
        if ($entity instanceof BusinessTemplate) {
257
            $em = $eventArgs->getEntityManager();
258
            $entities = $this->businessPageHelper->getEntitiesAllowed($entity, $em);
259
            foreach ($entities as $be) {
260
                $page = $this->businessPageBuilder->generateEntityPageFromTemplate(
261
                    $entity,
262
                    $be,
263
                    $em
264
                );
265
                $event = new ViewReferenceEvent($page);
266
                $this->dispatcher->dispatch(ViewReferenceEvents::REMOVE_VIEW_REFERENCE, $event);
267
            }
268
        }
269
    }
270
}
271