public function register(): void
{
$page_title = 'Регистрация';
$this->view->render('/users/register', [
'page_title' => $page_title
], 'default');
}
public function registerStore(): void
{
$fillable = ['name', 'email', 'password'];
$data = load_data($fillable);
$rules = [
'name' => [
'required' => true,
'min' => 3,
'max' => 20
],
'email' => [
'required' => true,
'min' => 5,
'max' => 20,
'email' => $data['email'],
'unique' => 'users:email'
],
'password' => [
'required' => true,
'min' => 5,
'max' => 20
]
];
$validation = $this->formValidator->validate($data, $rules);
if (!$validation->hasErrors()) {
$data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
$this->model->name = $data['name'];
$this->model->email = $data['email'];
$this->model->password = $data['password'];
if ($this->model->save()) {
redirect('/');
} else {
$_SESSION['erros']['flash'] = 'Ошибка регистрации';
redirect('/users/registerStore');
}
} else {
$_SESSION['errors'] = [];
$fields = array_keys($validation->getErrors());
foreach ($fields as $field) {
$_SESSION['errors'][$field] = $validation->listErrors($field);
}
redirect('/users/register');
}
}
<main>
<?php if (isset($_SESSION['errors']['flash'])): ?>
<p><?= isset($_SESSION['errors']['flash']) ?></p>
<?php endif; ?>
<form action="/users/registerStore" method="POST">
<p>
Имя: <input type="text" name="name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>">
<?= isset($_SESSION['errors']['name']) ? $_SESSION['errors']['name'] : '' ?>
</p>
<p>
Email: <input type="text" name="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>">
<?= isset($_SESSION['errors']['email']) ? $_SESSION['errors']['email'] : '' ?>
</p>
<p>
Пароль: <input type="password" name="password" value="<?= htmlspecialchars($_POST['password'] ?? '') ?>">
<?= isset($_SESSION['errors']['password']) ? $_SESSION['errors']['password'] : '' ?>
</p>
<p><button type="submit">Зарегистрироваться</button></p>
<?php unset($_SESSION['errors']) ?>
</form>
</main>