TicketController::registrationAction()   A
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 38
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 38
rs 9.0444
c 0
b 0
f 0
cc 6
nc 6
nop 2
1
<?php
2
3
namespace Application\Bundle\DefaultBundle\Controller;
4
5
use Application\Bundle\DefaultBundle\Entity\TicketCost;
6
use Application\Bundle\UserBundle\Entity\User;
7
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
8
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
9
use Stfalcon\Bundle\EventBundle\Entity\Event;
10
use Stfalcon\Bundle\EventBundle\Entity\Payment;
11
use Stfalcon\Bundle\EventBundle\Entity\Ticket;
12
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpFoundation\Response;
15
16
/**
17
 * Class TicketController.
18
 */
19
class TicketController extends Controller
20
{
21
    /**
22
     * Show event ticket status (for current user).
23
     *
24
     * @param Event      $event
25
     * @param string     $position
26
     * @param TicketCost $ticketCost
27
     *
28
     * @return Response
29
     */
30
    public function statusAction(Event $event, $position = 'card', TicketCost $ticketCost = null)
31
    {
32
        $result = $this->get('stfalcon_event.ticket.service')->getTicketHtmlData(
33
            $event,
34
            $position,
35
            $ticketCost
36
        );
37
38
        return $this->render('@ApplicationDefault/Redesign/Event/event.ticket.status.html.twig', $result);
39
    }
40
41
    /**
42
     * Generating ticket with QR-code to event.
43
     *
44
     * @Route("/event/{eventSlug}/ticket", name="event_ticket_download")
45
     * @Route("/event/{eventSlug}/ticket/{asHtml}", name="event_ticket_download_html")
46
     *
47
     * @Security("has_role('ROLE_USER')")
48
     *
49
     * @param string $eventSlug
50
     * @param string $asHtml
51
     *
52
     * @return array|Response
53
     */
54
    public function downloadAction($eventSlug, $asHtml = null)
55
    {
56
        $event = $this->getDoctrine()
57
            ->getRepository('StfalconEventBundle:Event')->findOneBy(['slug' => $eventSlug]);
58
        /** @var User $user */
59
        $user = $this->getUser();
60
        /** @var Ticket $ticket */
61
        $ticket = $this->getDoctrine()->getManager()->getRepository('StfalconEventBundle:Ticket')
62
            ->findOneBy(['event' => $event->getId(), 'user' => $user->getId()]);
63
64
        if (!$ticket || !$ticket->isPaid()) {
0 ignored issues
show
introduced by
$ticket is of type Stfalcon\Bundle\EventBundle\Entity\Ticket, thus it always evaluated to true.
Loading history...
65
            return new Response('Вы не оплачивали участие в "'.$event->getName().'"', 402);
66
        }
67
68
        /** @var $pdfGen \Stfalcon\Bundle\EventBundle\Helper\NewPdfGeneratorHelper */
69
        $pdfGen = $this->get('app.helper.new_pdf_generator');
70
71
        $html = $pdfGen->generateHTML($ticket);
72
73
        if ('html' === $asHtml && 'test' === $this->getParameter('kernel.environment')) {
74
            return new Response(
75
                $html,
76
                200,
77
                [
78
                    'Content-Type' => 'application/txt',
79
                    'Content-Disposition' => sprintf('attach; filename="%s"', $ticket->generatePdfFilename()),
80
                ]
81
            );
82
        }
83
84
        return new Response(
85
            $pdfGen->generatePdfFile($ticket, $html),
86
            200,
87
            [
88
                'Content-Type' => 'application/pdf',
89
                'Content-Disposition' => sprintf('attach; filename="%s"', $ticket->generatePdfFilename()),
90
            ]
91
        );
92
    }
93
94
    /**
95
     * Check that QR-code is valid, and register ticket.
96
     *
97
     * @param Ticket $ticket Ticket
98
     * @param string $hash   Hash
99
     *
100
     * @return Response
101
     *
102
     * @Route("/ticket/{ticket}/check/{hash}", name="event_ticket_registration")
103
     */
104
    public function registrationAction(Ticket $ticket, $hash)
105
    {
106
        //bag fix test ticket.feature:27
107
        // сверяем хеш билета и хеш из урла
108
        if ($ticket->getHash() !== $hash) {
109
            return new Response('<h1 style="color:red">Невалидный хеш для билета №'.$ticket->getId().'</h1>', 403);
110
        }
111
112
        //bag fix test ticket.feature:33
113
        // любопытных пользователей перенаправляем на страницу события
114
        if (!$this->get('security.authorization_checker')->isGranted('ROLE_VOLUNTEER')) {
115
            return $this->redirect($this->generateUrl('event_show', ['eventSlug' => $ticket->getEvent()->getSlug()]));
116
        }
117
118
        // проверяем существует ли оплата
119
        if ($ticket->getPayment() instanceof Payment) {
0 ignored issues
show
introduced by
$ticket->getPayment() is always a sub-type of Stfalcon\Bundle\EventBundle\Entity\Payment.
Loading history...
120
            // проверяем оплачен ли билет
121
            if ($ticket->getPayment()->isPaid()) {
122
                // проверяем или билет ещё не отмечен как использованный
123
                if ($ticket->isUsed()) {
124
                    $timeNow = new \DateTime();
125
                    $timeDiff = $timeNow->diff($ticket->getUpdatedAt());
126
127
                    return new Response('<h1 style="color:orange">Билет №'.$ticket->getId().' был использован '.$timeDiff->format('%i мин. назад').'</h1>', 409);
128
                }
129
            } else {
130
                return new Response('<h1 style="color:orange">Билет №'.$ticket->getId().' не оплачен'.'</h1>');
131
            }
132
        } else {
133
            return new Response('<h1 style="color:orange">Билет №'.$ticket->getId().' оплата не существует'.'</h1>');
134
        }
135
136
        // отмечаем билет как использованный
137
        $em = $this->getDoctrine()->getManager();
138
        $ticket->setUsed(true);
139
        $em->flush();
140
141
        return new Response('<h1 style="color:green">Все ок. Билет №'.$ticket->getId().' отмечаем как использованный</h1>');
142
    }
143
}
144