TicketService::getTicketHtmlData()   F
last analyzed

Complexity

Conditions 48
Paths > 20000

Size

Total Lines 196
Code Lines 144

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 144
dl 0
loc 196
rs 0
c 0
b 0
f 0
cc 48
nc 130560
nop 3

How to fix   Long Method    Complexity   

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 Application\Bundle\DefaultBundle\Service;
4
5
use Application\Bundle\DefaultBundle\Entity\TicketCost;
6
use Application\Bundle\UserBundle\Entity\User;
7
use Doctrine\ORM\EntityManager;
8
use Stfalcon\Bundle\EventBundle\Entity\Event;
9
use Stfalcon\Bundle\EventBundle\Entity\Payment;
10
use Stfalcon\Bundle\EventBundle\Entity\Ticket;
11
use Stfalcon\Bundle\EventBundle\Entity\PromoCode;
12
use Symfony\Component\HttpFoundation\RequestStack;
13
use Symfony\Component\Routing\RouterInterface;
14
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
15
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
16
use Symfony\Component\Translation\TranslatorInterface;
17
18
/**
19
 * Сервис для работы с билетами.
20
 */
21
class TicketService
22
{
23
    const CAN_BUY_TICKET = 'can buy ticket';
24
    const CAN_DOWNLOAD_TICKET = 'can download ticket';
25
    const TICKETS_SOLD_OUT = 'all tickets sold out';
26
    const CAN_WANNA_VISIT = 'can wanna visit';
27
    const WAIT_FOR_PAYMENT_RECEIVE = 'wit for payment receive';
28
    const PAID_FOR_ANOTHER = 'paid for another';
29
    const PAID_IS_RETURNED = 'paid is return';
30
    const EVENT_DONE = 'event done';
31
    const EVENT_DEFAULT_STATE = 'event default state';
32
33
    /** @var EntityManager */
34
    protected $em;
35
36
    /** @var array */
37
    protected $paymentsConfig;
38
39
    /** @var TranslatorInterface */
40
    protected $translator;
41
42
    /** @var RouterInterface */
43
    protected $router;
44
45
    /** @var TicketCostService */
46
    protected $ticketCostService;
47
48
    /** @var TokenStorageInterface */
49
    protected $tokenStorage;
50
51
    /**
52
     * TicketService constructor.
53
     *
54
     * @param EntityManager         $em
55
     * @param array                 $paymentsConfig
56
     * @param TranslatorInterface   $translator
57
     * @param RouterInterface       $router
58
     * @param TicketCostService     $ticketCostService
59
     * @param TokenStorageInterface $tokenStorage
60
     */
61
    public function __construct($em, $paymentsConfig, $translator, $router, $ticketCostService, TokenStorageInterface $tokenStorage)
62
    {
63
        $this->em = $em;
64
        $this->paymentsConfig = $paymentsConfig;
65
        $this->translator = $translator;
66
        $this->router = $router;
67
        $this->ticketCostService = $ticketCostService;
68
        $this->tokenStorage = $tokenStorage;
69
    }
70
71
    /**
72
     * Check discount for ticket.
73
     *
74
     * @param Ticket $ticket
75
     *
76
     * @return bool
77
     */
78
    public function isMustBeDiscount($ticket)
79
    {
80
        $event = $ticket->getEvent();
81
        $user = $ticket->getUser();
82
83
        if (!$event->getUseDiscounts()) {
84
            return false;
85
        }
86
87
        $paidPayments = $this->em->getRepository('StfalconEventBundle:Payment')
88
            ->findPaidPaymentsForUser($user);
89
90
        return \count($paidPayments) > 0;
91
    }
92
93
    /**
94
     * Set Ticket Amount with recalculate discount.
95
     *
96
     * @param Ticket     $ticket
97
     * @param float      $amount
98
     * @param bool       $isMustBeDiscount
99
     * @param TicketCost $currentTicketCost
100
     */
101
    public function setTicketAmount($ticket, $amount, $isMustBeDiscount, $currentTicketCost)
102
    {
103
        $ticket->setAmountWithoutDiscount($amount);
104
        $ticket->setAmount($amount);
105
        $ticket->setTicketCost($currentTicketCost);
106
        /** -1 flag means you need to discount in the configuration */
107
        $discount = $isMustBeDiscount ? -1 : 0;
108
        $this->setTicketBestDiscount($ticket, $ticket->getPromoCode(), $discount);
109
    }
110
111
    /**
112
     * Set the best (from promo code or standard discount) discount for ticket.
113
     *
114
     * @param Ticket    $ticket
115
     * @param PromoCode $promoCode
116
     * @param float     $discount
117
     *
118
     * @return Ticket
119
     */
120
    public function setTicketBestDiscount($ticket, $promoCode, $discount = -1)
121
    {
122
        if (-1 === $discount) {
123
            $discount = (float) $this->paymentsConfig['discount'];
124
        }
125
        if ($promoCode instanceof PromoCode && $promoCode->getDiscountAmount() / 100 > $discount) {
126
            $this->setTicketPromoCode($ticket, $promoCode);
127
        } else {
128
            $ticket->setPromoCode(null);
129
            $this->setTicketDiscount($ticket, $discount);
130
        }
131
132
        return $ticket;
133
    }
134
135
    /**
136
     * Set Ticket promo-code.
137
     *
138
     * @param Ticket    $ticket
139
     * @param PromoCode $promoCode
140
     *
141
     * @return Ticket
142
     */
143
    public function setTicketPromoCode($ticket, $promoCode)
144
    {
145
        $ticket->setPromoCode($promoCode);
146
        $this->setTicketDiscount($ticket, $promoCode->getDiscountAmount() / 100);
147
        $promoCode->incTmpUsedCount();
148
149
        return $ticket;
150
    }
151
152
    /**
153
     * Set ticket discount.
154
     *
155
     * @param Ticket $ticket
156
     * @param float  $discount
157
     *
158
     * @return Ticket
159
     */
160
    public function setTicketDiscount($ticket, $discount)
161
    {
162
        $amountWithDiscount = $ticket->getAmountWithoutDiscount() - ($ticket->getAmountWithoutDiscount() * $discount);
163
        $ticket
164
            ->setAmount($amountWithDiscount)
165
            ->setHasDiscount((float) $ticket->getAmount() !== (float) $ticket->getAmountWithoutDiscount());
166
        $this->em->flush();
167
168
        return $ticket;
169
    }
170
171
    /**
172
     * Create ticket for User and Event.
173
     *
174
     * @param Event $event
175
     * @param User  $user
176
     *
177
     * @return Ticket
178
     */
179
    public function createTicket($event, $user)
180
    {
181
        $ticket = (new Ticket())
182
            ->setEvent($event)
183
            ->setUser($user)
184
            ->setAmountWithoutDiscount($event->getCost())
185
            ->setAmount($event->getCost());
186
        $this->em->persist($ticket);
187
        $this->em->flush();
188
189
        return $ticket;
190
    }
191
192
    /**
193
     * @param Event           $event
194
     * @param string          $position
195
     * @param TicketCost|null $ticketCost
196
     *
197
     * @return array
198
     */
199
    public function getTicketHtmlData($event, $position, $ticketCost)
200
    {
201
        $ticket = null;
202
        /** @var Payment $payment */
203
        $payment = null;
204
205
        $token = $this->tokenStorage->getToken();
206
207
        $user = $token instanceof TokenInterface && $token->getUser() instanceof User ? $token->getUser() : null;
208
        if ($user instanceof User) {
209
            $payment = $this->em
210
                ->getRepository('StfalconEventBundle:Payment')
211
                ->findPaymentByUserAndEvent($user, $event);
212
213
            $ticket = $this->em->getRepository('StfalconEventBundle:Ticket')
214
                ->findOneBy(['event' => $event->getId(), 'user' => $user->getId()]);
215
        }
216
217
        $eventState = null;
218
        $ticketState = null;
219
        $isDiv = null;
220
        $data = null;
221
        $ticketClass = '';
222
        $href = null;
223
        $caption = '';
224
        $ticketCaption = '';
225
226
        if ($event->isActiveAndFuture()) {
227
            if ($ticket && $ticket->isPaid()) {
228
                $ticketState = self::CAN_DOWNLOAD_TICKET;
229
            }
230
            if ($ticket && !$event->getReceivePayments()) {
231
                $eventState = self::WAIT_FOR_PAYMENT_RECEIVE;
232
            } elseif ($payment && $payment->isPaid()) {
233
                $eventState = self::PAID_FOR_ANOTHER;
234
//            } elseif ($event->getTicketsCost()->count() > 0 && !$this->ticketCostService->isEventHaveTickets($event)) {
235
//                $eventState = self::TICKETS_SOLD_OUT;
236
            } elseif (!$event->getReceivePayments()) {
237
                $eventState = self::CAN_WANNA_VISIT;
238
            } elseif (!$event->isHaveFreeTickets()) {
239
                $eventState = self::TICKETS_SOLD_OUT;
240
            } elseif (!$payment || ($payment && $payment->isPending())) {
241
                $eventState = self::CAN_BUY_TICKET;
242
            } elseif ($payment && $payment->isReturned()) {
243
                $eventState = self::PAID_IS_RETURNED;
244
            }
245
        } else {
246
            $eventState = self::EVENT_DONE;
247
        }
248
249
        $states =
250
            [
251
                'row' => [
252
                        self::CAN_DOWNLOAD_TICKET => '',
253
                        self::EVENT_DONE => 'event-row__status',
254
                        self::EVENT_DEFAULT_STATE => 'event-row__btn btn btn--primary btn--sm',
255
                    ],
256
                'card' => [
257
                        self::CAN_DOWNLOAD_TICKET => 'event-card__download',
258
                        self::EVENT_DONE => 'event-card__status',
259
                        self::EVENT_DEFAULT_STATE => 'btn btn--primary btn--sm event-card__btn',
260
                    ],
261
                'event_header' => [
262
                        self::CAN_DOWNLOAD_TICKET => 'event-card__download',
263
                        self::EVENT_DONE => 'event-header__status',
264
                        self::EVENT_DEFAULT_STATE => 'btn btn--primary btn--lg event-header__btn',
265
                    ],
266
                'event_fix_header' => [
267
                        self::CAN_DOWNLOAD_TICKET => '',
268
                        self::EVENT_DONE => 'fix-event-header__status',
269
                        self::EVENT_DEFAULT_STATE => 'btn btn--primary btn--lg fix-event-header__btn',
270
                    ],
271
                'event_fix_header_mob' => [
272
                        self::CAN_DOWNLOAD_TICKET => '',
273
                        self::EVENT_DONE => 'fix-event-header__status fix-event-header__status--mob',
274
                        self::EVENT_DEFAULT_STATE => 'btn btn--primary btn--lg fix-event-header__btn fix-event-header__btn--mob',
275
                    ],
276
                'event_action_mob' => [
277
                        self::CAN_DOWNLOAD_TICKET => 'event-action-mob__download',
278
                        self::EVENT_DONE => 'event-action-mob__status',
279
                        self::EVENT_DEFAULT_STATE => 'btn btn--primary btn--lg event-action-mob__btn',
280
                    ],
281
                'price_block_mob' => [
282
                        self::CAN_DOWNLOAD_TICKET => '',
283
                        self::EVENT_DEFAULT_STATE => 'btn btn--primary btn--lg cost__buy cost__buy--mob',
284
                    ],
285
                'price_block' => [
286
                        self::CAN_DOWNLOAD_TICKET => '',
287
                        self::EVENT_DEFAULT_STATE => 'btn btn--primary btn--lg cost__buy',
288
                    ],
289
            ];
290
291
        if (in_array(
292
            $eventState,
293
            [
294
                self::EVENT_DONE,
295
                self::PAID_IS_RETURNED,
296
                self::PAID_FOR_ANOTHER,
297
                self::TICKETS_SOLD_OUT,
298
            ]
299
        )) {
300
            $class = isset($states[$position][self::EVENT_DONE]) ? $states[$position][self::EVENT_DONE]
301
                : $states[$position][self::EVENT_DEFAULT_STATE];
302
        } else {
303
            $class = isset($states[$position][$eventState]) ? $states[$position][$eventState]
304
                : $states[$position][self::EVENT_DEFAULT_STATE];
305
        }
306
307
        $isMob = in_array($position, ['event_fix_header_mob', 'price_block_mob']);
308
309
        if ($event->isActiveAndFuture()) {
310
            $data = $event->getSlug();
311
312
            if (self::CAN_DOWNLOAD_TICKET === $ticketState) {
313
                $ticketCaption = $isMob ? $this->translator->trans('ticket.status.download')
314
                    : $this->translator->trans('ticket.status.download');
315
                $ticketClass = isset($states[$position][$ticketState]) ? $states[$position][$ticketState]
316
                    : $states[$position][self::EVENT_DEFAULT_STATE];
317
                if (!empty($ticketClass)) {
318
                    $href = $this->router->generate('event_ticket_download', ['eventSlug' => $event->getSlug()]);
319
                }
320
            }
321
322
            if (self::WAIT_FOR_PAYMENT_RECEIVE === $eventState) {
323
                $caption = $this->translator->trans('ticket.status.event.add');
324
                $isDiv = true;
325
            } elseif (self::PAID_FOR_ANOTHER === $eventState) {
326
                if ($isMob) {
327
                    $caption = $this->translator->trans('ticket.status.paid_mob');
328
                } else {
329
                    $caption = $this->translator->trans('ticket.status.paid');
330
                }
331
            } elseif (self::TICKETS_SOLD_OUT === $eventState) {
332
                $isDiv = true;
333
                if ($isMob) {
334
                    $caption = $this->translator->trans('ticket.status.sold_mob');
335
                } else {
336
                    $caption = $this->translator->trans('ticket.status.sold');
337
                }
338
            } elseif (self::CAN_WANNA_VISIT === $eventState && (!$user || !$user->isEventInWants($event))) {
339
                $class .= ' set-modal-header add-wants-visit-event';
340
                $caption = $this->translator->trans('ticket.status.take_apart');
341
            } elseif (self::CAN_WANNA_VISIT === $eventState && ($user && $user->isEventInWants($event))) {
342
                $class .= ' set-modal-header sub-wants-visit-event';
343
                $caption = $this->translator->trans('ticket.status.not_take_apart');
344
            } elseif (self::CAN_BUY_TICKET === $eventState) {
345
                if ($isMob) {
346
                    $caption = $this->translator->trans('ticket.mob_status.pay');
347
                } elseif ('price_block' === $position) {
348
                    $amount = $ticketCost ? $ticketCost->getAmount() : $event->getBiggestTicketCost()->getAmount();
349
                    $altAmount = $ticketCost ? '≈$'.number_format($ticketCost->getAltAmount(), 0, ',', ' ') : '';
350
                    $caption = $this->translator->trans('ticket.status.pay_for').' '.$this->translator
351
                            ->trans(
352
                                'payment.price',
353
                                [
354
                                    '%summ%' => number_format($amount, 0, ',', ' '),
355
                                ]
356
                            );
357
                    if ($ticketCost && $ticketCost->getAltAmount()) {
358
                        $caption .= '<span class="cost__dollars">'.$altAmount.'</span>';
359
                    }
360
                } else {
361
                    $caption = $this->translator->trans('ticket.status.pay');
362
                }
363
                if (!in_array($position, ['event_header', 'event_fix_header', 'event_fix_header_mob'])) {
364
                    $class .= ' get-payment';
365
                }
366
            } elseif (self::PAID_IS_RETURNED === $eventState) {
367
                if ($isMob) {
368
                    $caption = $this->translator->trans('ticket.status.payment_returned_mob');
369
                } else {
370
                    $caption = $this->translator->trans('ticket.status.payment_returned');
371
                }
372
            }
373
        } else {
374
            $isDiv = true;
375
            if ($isMob) {
376
                $caption = $this->translator->trans('ticket.status.event_done_mob');
377
            } else {
378
                $caption = $this->translator->trans('ticket.status.event_done');
379
            }
380
        }
381
382
        $result =
383
            [
384
                'class' => $class,
385
                'caption' => $caption,
386
                'ticket_caption' => $ticketCaption,
387
                'ticket_class' => $ticketClass,
388
                'href' => $href,
389
                'isDiv' => $isDiv,
390
                'data' => $data,
391
                'id' => $position.'-'.$data,
392
            ];
393
394
        return $result;
395
    }
396
}
397