Test Failed
Pull Request — master (#476)
by
unknown
03:09
created

SignupController::signup()   B

Complexity

Conditions 8
Paths 7

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 8.048

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 8
eloc 18
c 1
b 0
f 1
nc 7
nop 4
dl 0
loc 32
ccs 10
cts 11
cp 0.9091
crap 8.048
rs 8.4444
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Auth\Controller;
6
7
use App\Auth\AuthService;
8
use App\Auth\Form\SignupForm;
9
use App\Service\WebControllerService;
10
use App\User\UserLoginException;
11
use App\User\UserPasswordException;
12
use Psr\Http\Message\ResponseInterface;
13
use Psr\Http\Message\ServerRequestInterface;
14
use Yiisoft\Http\Method;
15
use Yiisoft\Translator\TranslatorInterface;
16
use Yiisoft\Validator\ValidatorInterface;
17
use Yiisoft\Yii\View\ViewRenderer;
18
19
final class SignupController
20
{
21
    private ViewRenderer $viewRenderer;
22 5
    private WebControllerService $webService;
23
24 5
    public function __construct(ViewRenderer $viewRenderer, WebControllerService $webService)
25 5
    {
26
        $this->viewRenderer = $viewRenderer->withControllerName('signup');
27
        $this->webService = $webService;
28 5
    }
29
30
    public function signup(
31
        AuthService $authService,
32
        ServerRequestInterface $request,
33
        TranslatorInterface $translator,
34 5
        ValidatorInterface $validator
35
    ): ResponseInterface {
36
        if (!$authService->isGuest()) {
37
            return $this->redirectToMain();
38 5
        }
39
40 5
        $body = $request->getParsedBody();
41
42
        $signupForm = new SignupForm($translator);
43 5
44 4
        if (
45 4
            $request->getMethod() === Method::POST
46
            && $signupForm->load(is_array($body) ? $body : [])
47 1
            && $validator
48
                ->validate($signupForm)
49
                ->isValid()
50 5
        ) {
51
            try {
52
                $authService->signup($signupForm->getLogin(), $signupForm->getPassword());
53 1
                return $this->redirectToMain();
54
            } catch (UserLoginException $exception) {
55 1
                $signupForm->getFormErrors()->addError('login', $exception->getMessage());
56
            } catch (UserPasswordException $exception) {
57
                $signupForm->getFormErrors()->addError('password', $exception->getMessage());
58
            }
59
        }
60
61
        return $this->viewRenderer->render('signup', ['formModel' => $signupForm]);
62
    }
63
64
    private function redirectToMain(): ResponseInterface
65
    {
66
        return $this->webService->getRedirectResponse('site/index');
67
    }
68
}
69