Passed
Push — dependabot/npm_and_yarn/nanoid... ( aaf2c9...c4aa90 )
by
unknown
14:37 queued 06:22
created

ValidationTokenHelper::generateLink()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
nc 1
nop 2
dl 0
loc 10
rs 10
c 2
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\ServiceHelper;
8
9
use Chamilo\CoreBundle\Entity\ValidationToken;
10
use Chamilo\CoreBundle\Repository\ValidationTokenRepository;
11
use InvalidArgumentException;
12
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
13
14
class ValidationTokenHelper
15
{
16
    // Define constants for the types
17
    public const TYPE_TICKET = 1;
18
    public const TYPE_USER = 2;
19
20
    public function __construct(
21
        private readonly ValidationTokenRepository $tokenRepository,
22
        private readonly UrlGeneratorInterface $urlGenerator,
23
    ) {}
24
25
    public function generateLink(int $type, int $resourceId): string
26
    {
27
        $token = new ValidationToken($type, $resourceId);
28
        $this->tokenRepository->save($token, true);
29
30
        // Generate a validation link with the token's hash
31
        return $this->urlGenerator->generate('validate_token', [
32
            'type' => $this->getTypeString($type),
33
            'hash' => $token->getHash(),
34
        ], UrlGeneratorInterface::ABSOLUTE_URL);
35
    }
36
37
    public function getTypeId(string $type): int
38
    {
39
        return match ($type) {
40
            'ticket' => self::TYPE_TICKET,
41
            'user' => self::TYPE_USER,
42
            default => throw new InvalidArgumentException('Unrecognized validation type'),
43
        };
44
    }
45
46
    private function getTypeString(int $type): string
47
    {
48
        return match ($type) {
49
            self::TYPE_TICKET => 'ticket',
50
            self::TYPE_USER => 'user',
51
            default => throw new InvalidArgumentException('Unrecognized validation type'),
52
        };
53
    }
54
}
55