|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace App\Auth\Controller; |
|
6
|
|
|
|
|
7
|
|
|
use App\Auth\AuthService; |
|
8
|
|
|
use InvalidArgumentException; |
|
9
|
|
|
use Psr\Http\Message\ResponseFactoryInterface; |
|
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
11
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
12
|
|
|
use Psr\Log\LoggerInterface; |
|
13
|
|
|
use Throwable; |
|
14
|
|
|
use Yiisoft\Http\Method; |
|
15
|
|
|
use Yiisoft\Http\Status; |
|
16
|
|
|
use Yiisoft\Router\UrlGeneratorInterface; |
|
17
|
|
|
use Yiisoft\Yii\View\ViewRenderer; |
|
18
|
|
|
|
|
19
|
|
|
final class SignupController |
|
20
|
|
|
{ |
|
21
|
|
|
private ViewRenderer $viewRenderer; |
|
22
|
|
|
private UrlGeneratorInterface $urlGenerator; |
|
23
|
|
|
private ResponseFactoryInterface $responseFactory; |
|
24
|
|
|
|
|
25
|
|
|
public function __construct( |
|
26
|
|
|
ViewRenderer $viewRenderer, |
|
27
|
|
|
UrlGeneratorInterface $urlGenerator, |
|
28
|
|
|
ResponseFactoryInterface $responseFactory, |
|
29
|
|
|
) { |
|
30
|
|
|
$this->viewRenderer = $viewRenderer->withControllerName('signup'); |
|
31
|
|
|
$this->urlGenerator = $urlGenerator; |
|
32
|
|
|
$this->responseFactory = $responseFactory; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
public function signup( |
|
36
|
|
|
ServerRequestInterface $request, |
|
37
|
|
|
LoggerInterface $logger, |
|
38
|
|
|
AuthService $authService, |
|
39
|
|
|
): ResponseInterface { |
|
40
|
|
|
if (!$authService->isGuest()) { |
|
41
|
|
|
return $this->redirectToMain(); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
$body = $request->getParsedBody(); |
|
45
|
|
|
$error = null; |
|
46
|
|
|
|
|
47
|
|
|
if ($request->getMethod() === Method::POST) { |
|
48
|
|
|
try { |
|
49
|
|
|
foreach (['login', 'password'] as $name) { |
|
50
|
|
|
if (empty($body[$name])) { |
|
51
|
|
|
throw new InvalidArgumentException(ucfirst($name) . ' is required.'); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$authService->signup($body['login'], $body['password']); |
|
56
|
|
|
return $this->redirectToMain(); |
|
57
|
|
|
} catch (Throwable $e) { |
|
58
|
|
|
$logger->error($e); |
|
59
|
|
|
$error = $e->getMessage(); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
return $this->viewRenderer->render('signup', [ |
|
64
|
|
|
'body' => $body, |
|
65
|
|
|
'error' => $error, |
|
66
|
|
|
]); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
private function redirectToMain(): ResponseInterface |
|
70
|
|
|
{ |
|
71
|
|
|
return $this->responseFactory->createResponse(Status::FOUND) |
|
72
|
|
|
->withHeader( |
|
73
|
|
|
'Location', |
|
74
|
|
|
$this->urlGenerator->generate('site/index') |
|
75
|
|
|
); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|