Completed
Pull Request — master (#251)
by
unknown
02:45
created

RegistrationController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 5
cts 5
cp 1
rs 9.9
c 0
b 0
f 0
cc 1
nc 1
nop 5
crap 1
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-usuario project.
5
 *
6
 * (c) 2amigOS! <http://2amigos.us/>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace Da\User\Controller;
13
14
use Da\User\Event\FormEvent;
15
use Da\User\Event\SocialNetworkConnectEvent;
16
use Da\User\Event\UserEvent;
17
use Da\User\Factory\MailFactory;
18
use Da\User\Form\RegistrationForm;
19
use Da\User\Form\ResendForm;
20
use Da\User\Model\SocialNetworkAccount;
21
use Da\User\Model\User;
22
use Da\User\Query\SocialNetworkAccountQuery;
23
use Da\User\Query\UserQuery;
24
use Da\User\Service\AccountConfirmationService;
25
use Da\User\Service\ResendConfirmationService;
26
use Da\User\Service\UserConfirmationService;
27
use Da\User\Service\UserCreateService;
28
use Da\User\Service\UserRegisterService;
29
use Da\User\Traits\ContainerAwareTrait;
30
use Da\User\Traits\ModuleAwareTrait;
31
use Da\User\Validator\AjaxRequestModelValidator;
32
use Yii;
33
use yii\base\Module;
34
use yii\filters\AccessControl;
35
use yii\web\Controller;
36
use yii\web\NotFoundHttpException;
37
38
class RegistrationController extends Controller
39
{
40
    use ContainerAwareTrait;
41
    use ModuleAwareTrait;
42
43
    protected $userQuery;
44
    protected $socialNetworkAccountQuery;
45
46
47
    /**
48
     * RegistrationController constructor.
49
     *
50
     * @param string                    $id
51
     * @param Module                    $module
52
     * @param UserQuery                 $userQuery
53
     * @param SocialNetworkAccountQuery $socialNetworkAccountQuery
54
     * @param array                     $config
55
     */
56 8
    public function __construct(
57
        $id,
58
        Module $module,
59
        UserQuery $userQuery,
60
        SocialNetworkAccountQuery $socialNetworkAccountQuery,
61
        array $config = []
62
    ) {
63 8
        $this->userQuery = $userQuery;
64 8
        $this->socialNetworkAccountQuery = $socialNetworkAccountQuery;
65 8
        parent::__construct($id, $module, $config);
66 8
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71 8
    public function behaviors()
72
    {
73
        return [
74 8
            'access' => [
75
                'class' => AccessControl::class,
76
                'rules' => [
77
                    [
78
                        'allow' => true,
79
                        'actions' => ['register', 'connect'],
80
                        'roles' => ['?'],
81
                    ],
82
                    [
83
                        'allow' => true,
84
                        'actions' => ['confirm', 'resend'],
85
                        'roles' => ['?', '@'],
86
                    ],
87
                ],
88
            ],
89
        ];
90
    }
91
92 6
    public function actionRegister()
93
    {
94 6
        if (!$this->module->enableRegistration) {
95
            throw new NotFoundHttpException();
96
        }
97
        /** @var RegistrationForm $form */
98 6
        $form = $this->make(RegistrationForm::class);
99
        /** @var FormEvent $event */
100 6
        $event = $this->make(FormEvent::class, [$form]);
101
102 6
        $this->make(AjaxRequestModelValidator::class, [$form])->validate();
103
104 6
        if ($form->load(Yii::$app->request->post()) && $form->validate()) {
105 6
            $this->trigger(FormEvent::EVENT_BEFORE_REGISTER, $event);
106
            /** @var User $user */
107 6
            $user = $this->make(User::class, [], $form->attributes);
108 6
            $user->setScenario('register');
109 6
            $mailService = MailFactory::makeWelcomeMailerService($user);
110
111 6
            if ($this->make(UserRegisterService::class, [$user, $mailService])->run()) {
112 6
                if ($this->module->enableEmailConfirmation) {
113 2
                    Yii::$app->session->setFlash(
114 2
                        'info',
115 2
                        Yii::t(
116 2
                            'usuario',
117 2
                            'Your account has been created and a message with further instructions has been sent to your email'
118
                        )
119
                    );
120
                } else {
121 4
                    Yii::$app->session->setFlash('info', Yii::t('usuario', 'Your account has been created'));
122
                }
123 6
                $this->trigger(FormEvent::EVENT_AFTER_REGISTER, $event);
124 6
                return $this->render(
125 6
                    '/shared/message',
126
                    [
127 6
                        'title' => Yii::t('usuario', 'Your account has been created'),
128 6
                        'module' => $this->module,
129
                    ]
130
                );
131
            }
132
            Yii::$app->session->setFlash('danger', Yii::t('usuario', 'User could not be registered.'));
133
        }
134 6
        return $this->render('register', ['model' => $form, 'module' => $this->module]);
135
    }
136
137
    public function actionConnect($code)
138
    {
139
        /** @var SocialNetworkAccount $account */
140
        $account = $this->socialNetworkAccountQuery->whereCode($code)->one();
141
        if ($account === null || $account->getIsConnected()) {
142
            throw new NotFoundHttpException();
143
        }
144
145
        /** @var User $user */
146
        $user = $this->make(
147
            User::class,
148
            [],
149
            ['scenario' => 'connect', 'username' => $account->username, 'email' => $account->email]
150
        );
151
        $event = $this->make(SocialNetworkConnectEvent::class, [$user, $account]);
152
153
        $this->make(AjaxRequestModelValidator::class, [$user])->validate();
154
155
        if ($user->load(Yii::$app->request->post()) && $user->validate()) {
156
            $this->trigger(SocialNetworkConnectEvent::EVENT_BEFORE_CONNECT, $event);
157
158
            $mailService = MailFactory::makeWelcomeMailerService($user);
159
            if ($this->make(UserCreateService::class, [$user, $mailService])->run()) {
160
                $account->connect($user);
161
                $this->trigger(SocialNetworkConnectEvent::EVENT_AFTER_CONNECT, $event);
162
163
                Yii::$app->user->login($user, $this->module->rememberLoginLifespan);
164
165
                return $this->goBack();
166
            }
167
        }
168
169
        return $this->render(
170
            'connect',
171
            [
172
                'model' => $user,
173
                'account' => $account,
174
            ]
175
        );
176
    }
177
178 1
    public function actionConfirm($id, $code)
179
    {
180
        /** @var User $user */
181 1
        $user = $this->userQuery->whereId($id)->one();
182
183 1
        if ($user === null || $this->module->enableEmailConfirmation === false) {
184
            throw new NotFoundHttpException();
185
        }
186
187
        /** @var UserEvent $event */
188 1
        $event = $this->make(UserEvent::class, [$user]);
189 1
        $userConfirmationService = $this->make(UserConfirmationService::class, [$user]);
190
191 1
        $this->trigger(UserEvent::EVENT_BEFORE_CONFIRMATION, $event);
192
193 1
        if ($this->make(AccountConfirmationService::class, [$code, $user, $userConfirmationService])->run()) {
194 1
            Yii::$app->user->login($user, $this->module->rememberLoginLifespan);
195 1
            Yii::$app->session->setFlash('success', Yii::t('usuario', 'Thank you, registration is now complete.'));
196
197 1
            $this->trigger(UserEvent::EVENT_AFTER_CONFIRMATION, $event);
198
        } else {
199 1
            Yii::$app->session->setFlash(
200 1
                'danger',
201 1
                Yii::t('usuario', 'The confirmation link is invalid or expired. Please try requesting a new one.')
202
            );
203
        }
204
205 1
        return $this->render(
206 1
            '/shared/message',
207
            [
208 1
                'title' => Yii::t('usuario', 'Account confirmation'),
209 1
                'module' => $this->module,
210
            ]
211
        );
212
    }
213
214 1
    public function actionResend()
215
    {
216 1
        if ($this->module->enableEmailConfirmation === false) {
217
            throw new NotFoundHttpException();
218
        }
219
        /** @var ResendForm $form */
220 1
        $form = $this->make(ResendForm::class);
221 1
        $event = $this->make(FormEvent::class, [$form]);
222
223 1
        $this->make(AjaxRequestModelValidator::class, [$form])->validate();
224
225 1
        if ($form->load(Yii::$app->request->post()) && $form->validate()) {
226
            /** @var User $user */
227 1
            $user = $this->userQuery->whereEmail($form->email)->one();
228 1
            $success = true;
229 1
            if ($user !== null) {
230 1
                $this->trigger(FormEvent::EVENT_BEFORE_RESEND, $event);
231 1
                $mailService = MailFactory::makeConfirmationMailerService($user);
232 1
                if ($success = $this->make(ResendConfirmationService::class, [$user, $mailService])->run()) {
233 1
                    $this->trigger(FormEvent::EVENT_AFTER_RESEND, $event);
234 1
                    Yii::$app->session->setFlash(
235 1
                        'info',
236 1
                        Yii::t(
237 1
                            'usuario',
238 1
                            'A message has been sent to your email address. It contains a confirmation link that you must click to complete registration.'
239
                        )
240
                    );
241
                }
242
            }
243 1
            if ($user === null || $success === false) {
244 1
                Yii::$app->session->setFlash(
245 1
                    'danger',
246 1
                    Yii::t(
247 1
                        'usuario',
248 1
                        'We couldn\'t re-send the mail to confirm your address. Please, verify is the correct email or if it has been confirmed already.'
249
                    )
250
                );
251
            }
252
253 1
            return $this->render(
254 1
                '/shared/message',
255
                [
256 1
                    'title' => $success
257 1
                        ? Yii::t('usuario', 'A new confirmation link has been sent')
258 1
                        : Yii::t('usuario', 'Unable to send confirmation link'),
259 1
                    'module' => $this->module,
260
                ]
261
            );
262
        }
263
264 1
        return $this->render(
265 1
            'resend',
266
            [
267 1
                'model' => $form,
268
            ]
269
        );
270
    }
271
}
272