Completed
Push — master ( 025e52...863689 )
by Gabriel
02:50
created

UserController::generatePassswordResetToken()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 27
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
cc 6
eloc 20
nc 8
nop 5
1
<?php
2
3
namespace Sinergi\Users\User;
4
5
use Interop\Container\ContainerInterface;
6
use Sinergi\Users\Container;
7
use Sinergi\Users\Throttle\Throttle;
8
use Sinergi\Users\User\Exception\EmailAlreadyConfirmedException;
9
use Sinergi\Users\User\Exception\EmailConfirmationTokenBlockedException;
10
use Sinergi\Users\User\Exception\EmailConfirmationTokenExpiredException;
11
use Sinergi\Users\User\Exception\InvalidEmailConfirmationTokenException;
12
use Sinergi\Users\User\Exception\InvalidUserException;
13
use Sinergi\Users\User\Exception\PasswordResetTokenBlockedException;
14
use Sinergi\Users\User\Exception\TooManyEmailConfirmationTokenAttemptsException;
15
use DateInterval;
16
use Sinergi\Users\User\Exception\UserNotFoundException;
17
18
class UserController
19
{
20
    private $container;
21
22
    public function __construct(ContainerInterface $container)
23
    {
24
        if ($container instanceof Container) {
25
            $this->container = $container;
26
        } else {
27
            $this->container = new Container($container);
28
        }
29
    }
30
31
    public function generateEmailConfirmationToken(
32
        UserEntityInterface $user,
33
        string $token = null,
34
        DateInterval $expiration = null,
35
        bool $save = true
36
    ): UserEntityInterface {
37
        if ($user->isEmailConfirmed()) {
38
            throw new EmailAlreadyConfirmedException;
39
        } elseif ($user->getEmailConfirmationToken() && !$user->hasEmailConfirmationTokenCooldownExpired()) {
40
            throw new EmailConfirmationTokenBlockedException;
41
        }
42
43
        $user->generateEmailConfirmationToken($token, $expiration);
44
        if ($save) {
45
            /** @var UserRepositoryInterface $userRepository */
46
            $userRepository = $this->container->get(UserRepositoryInterface::class);
47
            $userRepository->save($user);
48
        }
49
        return $user;
50
    }
51
52
    public function generatePassswordResetToken(
53
        string $email,
54
        string $token = null,
55
        DateInterval $expiration = null,
56
        string $ip = null,
57
        bool $save = true
58
    ): UserEntityInterface {
59
        if ($ip) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ip of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
60
            Throttle::throttle($ip);
61
        }
62
        /** @var UserRepositoryInterface $userRepository */
63
        $userRepository = $this->container->get(UserRepositoryInterface::class);
64
        $user = $userRepository->findByEmail($email);
65
        if (!$user) {
66
            throw new UserNotFoundException;
67
        } elseif ($user->getPasswordResetToken() && !$user->hasPasswordResetTokenCooldownExpired()) {
68
            throw new PasswordResetTokenBlockedException;
69
        }
70
71
        $user->generatePasswordResetToken($token, $expiration);
72
        if ($save) {
73
            /** @var UserRepositoryInterface $userRepository */
74
            $userRepository = $this->container->get(UserRepositoryInterface::class);
75
            $userRepository->save($user);
76
        }
77
        return $user;
78
    }
79
80
    public function confirmEmail(UserEntityInterface $user, string $emailConfirmationToken): UserEntityInterface
81
    {
82
        if ($user->isEmailConfirmed()) {
83
            throw new EmailAlreadyConfirmedException;
84
        } elseif ($user->hasEmailConfirmationTokenExpired()) {
85
            throw new EmailConfirmationTokenExpiredException;
86
        } elseif ($user->hasTooManyEmailConfirmationTokenAttempts()) {
87
            throw new TooManyEmailConfirmationTokenAttemptsException;
88
        }
89
90
        /** @var UserRepositoryInterface $userRepository */
91
        $userRepository = $this->container->get(UserRepositoryInterface::class);
92
93
        if ($user->getEmailConfirmationToken() !== $emailConfirmationToken) {
94
            $user->setEmailConfirmationTokenAttempts($user->getEmailConfirmationTokenAttempts() + 1);
95
            $userRepository->save($user);
96
            throw new InvalidEmailConfirmationTokenException;
97
        }
98
99
        $user->setIsEmailConfirmed(true);
100
        $user->setEmailConfirmationToken(null);
101
        $user->setEmailConfirmationTokenAttempts(0);
102
        $user->setEmailConfirmationTokenExpirationDatetime(null);
103
        $userRepository->save($user);
104
        return $user;
105
    }
106
107
    public function createUser(UserEntityInterface $user): UserEntityInterface
108
    {
109
        /** @var UserValidatorInterface $userValidator */
110
        $userValidator = $this->container->get(UserValidatorInterface::class);
111
        $errors = $userValidator($user);
112
113
        if (!empty($errors)) {
114
            throw new InvalidUserException($errors);
115
        }
116
117
        /** @var UserRepositoryInterface $userRepository */
118
        $userRepository = $this->container->get(UserRepositoryInterface::class);
119
        $userRepository->save($user);
120
121
        $this->getEmailConfirmationController()
0 ignored issues
show
Bug introduced by
The method getEmailConfirmationController() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
122
            ->sendConfirmationEmail($user);
123
124
        return $user;
125
    }
126
127
    /**
128
     * @param UserEntity $userEntity
129
     * @param array      $parameters
130
     */
131
    public function updateUser(UserEntity $userEntity, array $parameters)
132
    {
133
        $options = [UserValidator::OPTION_SKIP_PASSWORD_VALIDATION];
134
135
        //todo : refactored this :
136
137
        $parameters = array_merge($userEntity->toArray(), $parameters);
138
139
        if ($userEntity->getEmail() === $parameters['email']) {
140
            $options[] = UserValidator::OPTION_SKIP_EMAIL_UNIQUENESS;
141
        }
142
143
        $this->getUserValidator()->validateParameters($parameters, $options);
0 ignored issues
show
Bug introduced by
The method getUserValidator() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
144
145
        if ($userEntity->getEmail() !== $parameters['email']) {
146
            $userEntity->setPendingEmail($parameters['email']);
147
148
            (new EmailConfirmationController($this->getContainer()))->emailUpdated($userEntity);
0 ignored issues
show
Bug introduced by
The method getContainer() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
149
        }
150
151
        $userEntity
152
            ->setName($parameters['name'])
153
            ->setPhone($parameters['phone']);
154
155
        $this->getEntityManager()->persist($userEntity);
0 ignored issues
show
Bug introduced by
The method getEntityManager() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
156
        $this->getEntityManager()->flush($userEntity);
0 ignored issues
show
Bug introduced by
The method getEntityManager() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
157
    }
158
159
    /**
160
     * @param userEntity $userEntity
161
     * @param array      $parameters
162
     * @throws AuthenticationException
163
     */
164
    public function updatePassword(userEntity $userEntity, array $parameters)
165
    {
166
        if (!$userEntity->testPassword($parameters['current-password'])) {
167
            throw new AuthenticationException($this->getDictionary()->get('user.password.error.wrong_password'));
0 ignored issues
show
Bug introduced by
The method getDictionary() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
168
        }
169
170
        $this->getUserValidator()->validateParameters($parameters,
0 ignored issues
show
Bug introduced by
The method getUserValidator() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
171
            [UserValidator::OPTION_JUST_PASSWORD]);
172
173
        $userEntity->setPassword($parameters['password']);
174
        $this->getEntityManager()->persist($userEntity);
0 ignored issues
show
Bug introduced by
The method getEntityManager() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
175
        $this->getEntityManager()->flush($userEntity);
0 ignored issues
show
Bug introduced by
The method getEntityManager() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
176
    }
177
178
    /**
179
     * @param userEntity $userEntity
180
     */
181 View Code Duplication
    public function deleteUser(userEntity $userEntity)
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...
182
    {
183
        $userEntity->setStatus(UserEntity::STATUS_DELETED);
184
        $userEntity->setDeletedEmail($userEntity->getEmail());
185
        $userEntity->setEmail(null);
186
        $this->getContainer()->getEntityManager()->persist($userEntity);
0 ignored issues
show
Bug introduced by
The method getContainer() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
187
        $this->getContainer()->getEntityManager()->flush($userEntity);
0 ignored issues
show
Bug introduced by
The method getContainer() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
188
    }
189
190
    /**
191
     * @param userEntity $userEntity
192
     */
193 View Code Duplication
    public function banUser(userEntity $userEntity)
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...
194
    {
195
        $userEntity->setStatus(UserEntity::STATUS_BANNED);
196
        $userEntity->setDeletedEmail($userEntity->getEmail());
197
        $userEntity->setEmail(null);
198
        $this->getContainer()->getEntityManager()->persist($userEntity);
0 ignored issues
show
Bug introduced by
The method getContainer() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
199
        $this->getContainer()->getEntityManager()->flush($userEntity);
0 ignored issues
show
Bug introduced by
The method getContainer() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
200
    }
201
202
    /**
203
     * @param $status
204
     *
205
     * @return mixed
206
     */
207
    public function getUserStatusLabel($status)
208
    {
209
        switch ($status) {
210
            case UserEntity::STATUS_ACTIVE:
211
                return $this->getDictionary()->get('user.status.active');
0 ignored issues
show
Bug introduced by
The method getDictionary() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
212
            case UserEntity::STATUS_DELETED:
213
                return $this->getDictionary()->get('user.status.deleted');
0 ignored issues
show
Bug introduced by
The method getDictionary() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
214
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
215
            case UserEntity::STATUS_BANNED:
216
                return $this->getDictionary()->get('user.status.banned');
0 ignored issues
show
Bug introduced by
The method getDictionary() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
217
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
218
            default:
219
                return $this->getDictionary()->get('user.status.inactive');
0 ignored issues
show
Bug introduced by
The method getDictionary() does not seem to exist on object<Sinergi\Users\User\UserController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
220
        }
221
    }
222
}
223