|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
|
|
4
|
|
|
namespace App\Controller; |
|
5
|
|
|
|
|
6
|
|
|
use App\Controller; |
|
7
|
|
|
use App\Entity\User; |
|
8
|
|
|
use Cycle\ORM\ORMInterface; |
|
9
|
|
|
use Cycle\ORM\Transaction; |
|
10
|
|
|
use Psr\Http\Message\RequestInterface; |
|
11
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
12
|
|
|
use Psr\Log\LoggerInterface; |
|
13
|
|
|
use Yiisoft\Auth\IdentityRepositoryInterface; |
|
14
|
|
|
use Yiisoft\Http\Method; |
|
15
|
|
|
use Yiisoft\Router\UrlGeneratorInterface; |
|
16
|
|
|
|
|
17
|
|
|
final class SignupController extends Controller |
|
18
|
|
|
{ |
|
19
|
|
|
public function signup(RequestInterface $request, IdentityRepositoryInterface $identityRepository, ORMInterface $orm, UrlGeneratorInterface $urlGenerator, LoggerInterface $logger): ResponseInterface |
|
20
|
|
|
{ |
|
21
|
|
|
$body = $request->getParsedBody(); |
|
|
|
|
|
|
22
|
|
|
$error = null; |
|
23
|
|
|
|
|
24
|
|
|
if ($request->getMethod() === Method::POST) { |
|
25
|
|
|
try { |
|
26
|
|
|
foreach (['login', 'password'] as $name) { |
|
27
|
|
|
if (empty($body[$name])) { |
|
28
|
|
|
throw new \InvalidArgumentException(ucfirst($name) . ' is required.'); |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** @var \App\Entity\User $identity */ |
|
33
|
|
|
$identity = $identityRepository->findByLogin($body['login']); |
|
34
|
|
|
if ($identity !== null) { |
|
35
|
|
|
throw new \InvalidArgumentException('Unable to register user with such username.'); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
$user = new User($body['login'], $body['password']); |
|
39
|
|
|
|
|
40
|
|
|
$transaction = new Transaction($orm); |
|
41
|
|
|
$transaction->persist($user); |
|
42
|
|
|
|
|
43
|
|
|
$transaction->run(); |
|
44
|
|
|
return $this->responseFactory |
|
45
|
|
|
->createResponse(302) |
|
46
|
|
|
->withHeader( |
|
47
|
|
|
'Location', |
|
48
|
|
|
$urlGenerator->generate('site/index') |
|
49
|
|
|
); |
|
50
|
|
|
} catch (\Throwable $e) { |
|
51
|
|
|
$logger->error($e); |
|
52
|
|
|
$error = $e->getMessage(); |
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return $this->render( |
|
57
|
|
|
'signup', |
|
58
|
|
|
[ |
|
59
|
|
|
'body' => $body, |
|
60
|
|
|
'error' => $error, |
|
61
|
|
|
'csrf' => $request->getAttribute('csrf_token'), |
|
|
|
|
|
|
62
|
|
|
] |
|
63
|
|
|
); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|