Passed
Pull Request — master (#5831)
by
unknown
47:54 queued 24:36
created

ValidationTokenController::validateTicket()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 9
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Controller;
8
9
use Chamilo\CoreBundle\Entity\ValidationToken;
10
use Chamilo\CoreBundle\Repository\TrackEDefaultRepository;
11
use Chamilo\CoreBundle\Repository\ValidationTokenRepository;
12
use Chamilo\CoreBundle\ServiceHelper\ValidationTokenHelper;
13
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
14
use Symfony\Component\HttpFoundation\Response;
15
use Symfony\Component\Routing\Annotation\Route;
16
use Symfony\Component\Security\Core\Security;
17
18
#[Route('/validate')]
19
class ValidationTokenController extends AbstractController
20
{
21
    public function __construct(
22
        private readonly ValidationTokenHelper $validationTokenHelper,
23
        private readonly ValidationTokenRepository $tokenRepository,
24
        private readonly TrackEDefaultRepository $trackEDefaultRepository,
25
        private readonly Security $security
26
    ) {}
27
28
    #[Route('/{type}/{hash}', name: 'validate_token')]
29
    public function validate(string $type, string $hash): Response
30
    {
31
        $token = $this->tokenRepository->findOneBy([
32
            'type' => $this->validationTokenHelper->getTypeId($type),
33
            'hash' => $hash
34
        ]);
35
36
        if (!$token) {
37
            throw $this->createNotFoundException('Invalid token.');
38
        }
39
40
        // Process the action related to the token type
41
        $this->processAction($token);
42
43
        // Remove the used token
44
        $this->tokenRepository->remove($token, true);
45
46
        // Register the token usage event
47
        $this->registerTokenUsedEvent($token);
48
49
        return $this->render('@ChamiloCore/Validation/success.html.twig', [
50
            'type' => $type,
51
        ]);
52
    }
53
54
    #[Route('/test/generate-token/{type}/{resourceId}', name: 'test_generate_token')]
55
    public function testGenerateToken(string $type, int $resourceId): Response
56
    {
57
        $typeId = $this->validationTokenHelper->getTypeId($type);
58
        $token = new ValidationToken($typeId, $resourceId);
59
        $this->tokenRepository->save($token, true);
60
61
        $validationLink = $this->generateUrl('validate_token', [
62
            'type' => $type,
63
            'hash' => $token->getHash(),
64
        ], \Symfony\Component\Routing\Generator\UrlGeneratorInterface::ABSOLUTE_URL);
65
66
        return new Response("Generated token: {$token->getHash()}<br>Validation link: <a href='{$validationLink}'>{$validationLink}</a>");
67
    }
68
69
    private function processAction(ValidationToken $token): void
70
    {
71
        switch ($token->getType()) {
72
            case 1: // Assuming 1 is for 'ticket'
73
                $this->processTicketValidation($token);
74
                break;
75
            case 2: // Assuming 2 is for 'user'
76
                // Implement user validation logic here
77
                break;
78
            default:
79
                throw new \InvalidArgumentException('Unrecognized token type');
80
        }
81
    }
82
83
    private function processTicketValidation(ValidationToken $token): void
84
    {
85
        $ticketId = $token->getResourceId();
86
87
        // Simulate ticket validation logic
88
        // Here you would typically check if the ticket exists and is valid
89
        // For now, we'll just print a message to simulate this
90
        // Replace this with your actual ticket validation logic
91
        $ticketValid = $this->validateTicket($ticketId);
92
93
        if (!$ticketValid) {
94
            throw new \RuntimeException('Invalid ticket.');
95
        }
96
97
        // If the ticket is valid, you can mark it as used or perform other actions
98
        // For example, update the ticket status in the database
99
        // $this->ticketRepository->markAsUsed($ticketId);
100
    }
101
102
    private function validateTicket(int $ticketId): bool
103
    {
104
        // Here you would implement the logic to check if the ticket is valid.
105
        // This is a placeholder function to simulate validation.
106
107
        // For testing purposes, let's assume all tickets are valid.
108
        // In a real implementation, you would query your database or service.
109
110
        return true; // Assume the ticket is valid for now
111
    }
112
113
    private function registerTokenUsedEvent(ValidationToken $token): void
114
    {
115
        $user = $this->security->getUser();
116
        $userId = $user?->getId();
117
        $this->trackEDefaultRepository->registerTokenUsedEvent($token, $userId);
118
    }
119
}
120