EventController   C
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 313
Duplicated Lines 13.1 %

Coupling/Cohesion

Components 1
Dependencies 24

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 24
dl 41
loc 313
rs 5.238
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A confirmUnregistrationAction() 0 11 2
A __construct() 0 21 1
B registerAction() 0 35 5
B registerReviewAction() 0 62 5
B registerPaymentAction() 0 45 6
A unregisterAction() 20 20 2
A cancelTicketAction() 21 21 2
A participantListAction() 0 9 1

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
/**
4
 * @author    Markus Tacker <[email protected]>
5
 * @copyright 2013-2016 Verein zur Förderung der Netzkultur im Rhein-Main-Gebiet e.V. | http://netzkultur-rheinmain.de/
6
 */
7
8
namespace BCRM\WebBundle\Controller;
9
10
use BCRM\BackendBundle\Entity\Event\EventRepository;
11
use BCRM\BackendBundle\Entity\Event\Registration;
12
use BCRM\BackendBundle\Entity\Event\RegistrationRepository;
13
use BCRM\BackendBundle\Entity\Event\Ticket;
14
use BCRM\BackendBundle\Entity\Event\TicketRepository;
15
use BCRM\BackendBundle\Entity\Event\UnregistrationRepository;
16
use BCRM\BackendBundle\Service\Event\ConfirmUnregistrationCommand;
17
use BCRM\BackendBundle\Service\Event\RegisterCommand;
18
use BCRM\BackendBundle\Service\Event\UnregisterCommand;
19
use BCRM\WebBundle\Content\ContentReader;
20
use BCRM\WebBundle\Form\EventRegisterModel;
21
use BCRM\WebBundle\Form\EventRegisterType;
22
use BCRM\WebBundle\Form\EventUnregisterType;
23
use Carbon\Carbon;
24
use Dothiv\Bundle\MoneyFormatBundle\Service\MoneyFormatServiceInterface;
25
use LiteCQRS\Bus\CommandBus;
26
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
27
use Symfony\Component\Form\FormFactoryInterface;
28
use Symfony\Component\HttpFoundation\RedirectResponse;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpFoundation\Response;
31
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
32
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
33
use Symfony\Component\Routing\RouterInterface;
34
use Symfony\Component\Security\Core\Util\SecureRandom;
35
36
/**
37
 * Manages event registrations.
38
 */
39
class EventController
40
{
41
    /**
42
     * @var ContentReader
43
     */
44
    private $reader;
45
46
    /**
47
     * @var \Symfony\Component\Form\FormFactoryInterface
48
     */
49
    private $formFactory;
50
51
    /**
52
     * @var \Symfony\Component\Routing\RouterInterface
53
     */
54
    private $router;
55
56
    /**
57
     * @var \LiteCQRS\Bus\CommandBus
58
     */
59
    private $commandBus;
60
61
    /**
62
     * @var \BCRM\BackendBundle\Entity\Event\RegistrationRepository
63
     */
64
    private $registrationRepo;
65
66
    /**
67
     * @var \BCRM\BackendBundle\Entity\Event\EventRepository
68
     */
69
    private $eventRepo;
70
71
    /**
72
     * @var \BCRM\BackendBundle\Entity\Event\UnregistrationRepository
73
     */
74
    private $unregistrationRepo;
75
76
    /**
77
     * @var \BCRM\BackendBundle\Entity\Event\TicketRepository
78
     */
79
    private $ticketRepo;
80
81
    /**
82
     * @var MoneyFormatServiceInterface
83
     */
84
    private $moneyFormat;
85
86
    public function __construct(
87
        ContentReader $reader,
88
        FormFactoryInterface $formFactory,
89
        RouterInterface $router,
90
        CommandBus $commandBus,
91
        EventRepository $eventRepo,
92
        RegistrationRepository $registrationRepo,
93
        UnregistrationRepository $unregistrationRepo,
94
        TicketRepository $ticketRepo,
95
        MoneyFormatServiceInterface $moneyFormat)
96
    {
97
        $this->reader             = $reader;
98
        $this->formFactory        = $formFactory;
99
        $this->router             = $router;
100
        $this->commandBus         = $commandBus;
101
        $this->eventRepo          = $eventRepo;
102
        $this->registrationRepo   = $registrationRepo;
103
        $this->unregistrationRepo = $unregistrationRepo;
104
        $this->ticketRepo         = $ticketRepo;
105
        $this->moneyFormat        = $moneyFormat;
106
    }
107
108
    /**
109
     * @param Request $request
110
     *
111
     * @Template()
112
     */
113
    public function registerAction(Request $request)
114
    {
115
        $eventOptional = $this->eventRepo->getNextEvent();
116
        if (!$eventOptional->isDefined()) {
117
            return new RedirectResponse($this->router->generate('bcrmweb_registration_comingsoon'));
118
        }
119
        $event = $eventOptional->get();
120
        if (Carbon::createFromTimestamp($event->getRegistrationEnd()->getTimestamp())->isPast()) {
121
            throw new AccessDeniedHttpException('Registration not possible.');
122
        }
123
        $model          = new EventRegisterModel();
124
        $model->payment = 'paypal';
125
        if ($request->getSession()->has('registration')) {
126
            $model = $request->getSession()->get('registration');
127
        }
128
        $model->event = $event;
129
        $form         = $this->formFactory->create('event_register', $model,
130
            array(
131
                'action'            => $request->getPathInfo(),
132
                'validation_groups' => array('registration')
133
            )
134
        );
135
        $form->handleRequest($request);
136
        if ($form->isValid()) {
137
            $request->getSession()->set('registration', $form->getData());
138
            return new RedirectResponse($this->router->generate('bcrmweb_registration_review'));
139
        }
140
        return array(
141
            'sponsors'             => $this->reader->getPage('Sponsoren/Index.md'),
142
            'content'              => $this->reader->getPage('Registrierung/Intro.md'),
143
            'event'                => $event,
144
            'pricePerDayFormatted' => $this->moneyFormat->format($event->getPrice() / 100, 'de'),
145
            'form'                 => $form->createView(),
146
        );
147
    }
148
149
    /**
150
     * @param Request $request
151
     *
152
     * @Template()
153
     */
154
    public function registerReviewAction(Request $request)
155
    {
156
        $event = $this->eventRepo->getNextEvent()->getOrThrow(new AccessDeniedHttpException('No event.'));
157
        if (Carbon::createFromTimestamp($event->getRegistrationEnd()->getTimestamp())->isPast()) {
158
            throw new AccessDeniedHttpException('Registration not possible.');
159
        }
160
        /** @var EventRegisterModel $model */
161
        $model        = $request->getSession()->get('registration');
162
        $model->event = $event;
163
        $form         = $this->formFactory->create('event_register_review', $model,
164
            array(
165
                'action'            => $request->getPathInfo(),
166
                'validation_groups' => array('review')
167
            )
168
        );
169
        $form->handleRequest($request);
170
        if ($form->isValid()) {
171
            /* @var EventRegisterModel $formData */
172
            $formData                 = $form->getData();
173
            $command                  = new RegisterCommand();
174
            $command->event           = $event;
175
            $command->email           = $formData->email;
176
            $command->name            = $formData->name;
177
            $command->twitter         = $formData->twitter;
178
            $command->saturday        = $formData->wantsSaturday();
179
            $command->sunday          = $formData->wantsSunday();
180
            $command->food            = $formData->food;
181
            $command->participantList = $formData->participantList;
182
            $command->tags            = $formData->tags;
183
            $command->donation        = $formData->getDonation();
184
            $command->payment         = $formData->payment;
185
            $generator                = new SecureRandom();
186
            $command->uuid            = sha1($generator->nextBytes(16));
187
            $this->commandBus->handle($command);
188
            $request->getSession()->remove('registration');
189
            return new RedirectResponse($this->router->generate('bcrmweb_registration_ok'));
190
        }
191
        // TODO: Move to service
192
        $ticketPrice = ($model->days === 3 ? 2 : 1) * $event->getPrice();
193
        $orderTotal  = $model->getDonation() + $ticketPrice;
194
        $fees        = 0;
0 ignored issues
show
Unused Code introduced by
$fees 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...
195
        if ($model->payment === 'paypal') {
196
            //  Mit Paypal (zzgl. 1,9% + 0,35 Cent)
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
197
            $fees = ceil($orderTotal * 0.019) + 35;
198
        } else {
199
            // Mit barzahlen.de (zzgl. 3,0% + 0,35 Cent)
200
            $fees = ceil($orderTotal * 0.03) + 35;
201
        }
202
        $total = $model->getDonation() + $ticketPrice + $fees;
203
        return array(
204
            'sponsors'             => $this->reader->getPage('Sponsoren/Index.md'),
205
            'event'                => $event,
206
            'pricePerDayFormatted' => $this->moneyFormat->format($event->getPrice() / 100, 'de'),
207
            'ticketPriceFormatted' => $this->moneyFormat->format($ticketPrice / 100, 'de'),
208
            'donationFormatted'    => $this->moneyFormat->format($model->getDonation() / 100, 'de'),
209
            'orderTotalFormatted'  => $this->moneyFormat->format($orderTotal / 100, 'de'),
210
            'feesFormatted'        => $this->moneyFormat->format($fees / 100, 'de'),
211
            'totalFormatted'       => $this->moneyFormat->format($total / 100, 'de'),
212
            'form'                 => $form->createView(),
213
            'registration'         => $model,
214
        );
215
    }
216
217
    /**
218
     * @param Request $request
219
     *
220
     * @Template()
221
     *
222
     * @return array
223
     */
224
    public function registerPaymentAction($id, Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
225
    {
226
        $event = $this->eventRepo->getNextEvent()->getOrThrow(new AccessDeniedHttpException('No event.'));
227
        if (Carbon::createFromTimestamp($event->getRegistrationEnd()->getTimestamp())->isPast()) {
228
            throw new AccessDeniedHttpException('Registration not possible.');
229
        }
230
        $registrationOptional = $this->registrationRepo->getRegistrationByUuid($id);
231
        if ($registrationOptional->isEmpty()) {
232
            throw new NotFoundHttpException('Unknown registration.');
233
        }
234
        /** @var Registration $registration */
235
        $registration = $registrationOptional->get();
236
        $tickets      = $this->ticketRepo->getTicketsForEmail($event, $registration->getEmail());
237
        $numTickets   = count($tickets);
238
        // TODO: Move to service
239
        $registeredDays = 0;
240
        if ($registration->getSaturday()) {
241
            $registeredDays += 1;
242
        }
243
        if ($registration->getSunday()) {
244
            $registeredDays += 1;
245
        }
246
        $ticketPrice = $numTickets * $event->getPrice();
247
        $orderTotal  = $registration->getDonation() + $ticketPrice;
248
        $fees        = 0;
0 ignored issues
show
Unused Code introduced by
$fees 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...
249
        if ($registration->getPaymentMethod() === 'paypal') {
250
            //  Mit Paypal (zzgl. 1,9% + 0,35 Cent)
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
251
            $fees = ceil($orderTotal * 0.019) + 35;
252
        } else {
253
            // Mit barzahlen.de (zzgl. 3,0% + 0,35 Cent)
254
            $fees = ceil($orderTotal * 0.03) + 35;
255
        }
256
        $total = $registration->getDonation() + $ticketPrice + $fees;
257
258
        /** @var EventRegisterModel $model */
259
        return array(
260
            'sponsors'     => $this->reader->getPage('Sponsoren/Index.md'),
261
            'event'        => $event,
262
            'registration' => $registration,
263
            'total'        => $total,
264
            'tickets'      => $tickets,
265
            'partialOrder' => $registeredDays !== $numTickets,
266
            'days'         => $registeredDays
267
        );
268
    }
269
270
    /**
271
     * @param Request $request
272
     *
273
     * @Template()
274
     */
275 View Code Duplication
    public function unregisterAction(Request $request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
276
    {
277
        $form = $this->formFactory->create(new EventUnregisterType());
278
        $form->handleRequest($request);
279
        if ($form->isValid()) {
280
            /* @var EventRegisterModel $formData */
281
            $formData          = $form->getData();
282
            $command           = new UnregisterCommand();
283
            $command->event    = $this->eventRepo->getNextEvent()->getOrThrow(new AccessDeniedHttpException('No event.'));
284
            $command->email    = $formData->email;
285
            $command->saturday = $formData->wantsSaturday();
286
            $command->sunday   = $formData->wantsSunday();
287
            $this->commandBus->handle($command);
288
            return new RedirectResponse($this->router->generate('bcrmweb_unregistration_ok'));
289
        }
290
        return array(
291
            'sponsors' => $this->reader->getPage('Sponsoren/Index.md'),
292
            'form'     => $form->createView(),
293
        );
294
    }
295
296
    public function confirmUnregistrationAction($id, $key)
297
    {
298
        $unregistration = $this->unregistrationRepo->getUnregistrationByIdAndKey($id, $key);
299
        if ($unregistration->isEmpty()) {
300
            throw new NotFoundHttpException('Unknown unregistration.');
301
        }
302
        $command                 = new ConfirmUnregistrationCommand();
303
        $command->unregistration = $unregistration->get();
304
        $this->commandBus->handle($command);
305
        return new RedirectResponse($this->router->generate('bcrmweb_unregistration_confirmed'));
306
    }
307
308
    /**
309
     * @param Request $request
310
     * @param         $id
311
     * @param         $code
312
     *
313
     * @return array|RedirectResponse
314
     * @Template()
315
     */
316 View Code Duplication
    public function cancelTicketAction(Request $request, $id, $code)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
317
    {
318
        /* @var $ticket Ticket */
319
        $ticket = $this->ticketRepo->getTicketByIdAndCode($id, $code)->getOrThrow(new NotFoundHttpException('Unknown ticket.'));
320
321
        if ($request->isMethod('POST')) {
322
            $command            = new UnregisterCommand();
323
            $command->event     = $this->eventRepo->getNextEvent()->getOrThrow(new AccessDeniedHttpException('No event.'));
324
            $command->email     = $ticket->getEmail();
325
            $command->saturday  = $ticket->isSaturday();
326
            $command->sunday    = $ticket->isSunday();
327
            $command->confirmed = true;
328
            $this->commandBus->handle($command);
329
            return new RedirectResponse($this->router->generate('bcrmweb_unregistration_confirmed'));
330
        }
331
332
        return array(
333
            'ticket'   => $ticket,
334
            'sponsors' => $this->reader->getPage('Sponsoren/Index.md'),
335
        );
336
    }
337
338
    /**
339
     * @return Response
340
     * @Template()
341
     */
342
    public function participantListAction()
343
    {
344
        $event        = $this->eventRepo->getNextEvent()->getOrThrow(new AccessDeniedHttpException('No event.'));
345
        $participants = $this->registrationRepo->getParticipantList($event);
346
        return array(
347
            'participants' => $participants,
348
            'sponsors'     => $this->reader->getPage('Sponsoren/Index.md'),
349
        );
350
    }
351
}
352