Gère le cas où le login est déjà pris à l'inscription
This commit is contained in:
@@ -66,7 +66,8 @@ class DI
|
||||
private function getPDO(): PDO
|
||||
{
|
||||
if ($this->pdo === null) {
|
||||
return new PDO(sprintf('mysql:host=%s;dbname=%s', DB_HOST, DB_DATABASE), DB_USER, DB_PASSWORD);
|
||||
$this->pdo = new PDO(sprintf('mysql:host=%s;dbname=%s', DB_HOST, DB_DATABASE), DB_USER, DB_PASSWORD);
|
||||
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
}
|
||||
return $this->pdo;
|
||||
}
|
||||
|
15
src/Silex/Gateway/UniqueViolation.php
Normal file
15
src/Silex/Gateway/UniqueViolation.php
Normal file
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Silex\Gateway;
|
||||
|
||||
use PDOException;
|
||||
|
||||
final class UniqueViolation
|
||||
{
|
||||
public static function isUniqueViolation(PDOException $ex): bool
|
||||
{
|
||||
return $ex->errorInfo[1] === 1062; // Mysql
|
||||
}
|
||||
}
|
@@ -5,6 +5,7 @@ declare(strict_types=1);
|
||||
namespace Silex\Gateway;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Silex\Model\User;
|
||||
|
||||
class UserGateway
|
||||
@@ -37,7 +38,14 @@ class UserGateway
|
||||
public function insert(User $user): bool
|
||||
{
|
||||
$req = $this->pdo->prepare('INSERT INTO registered_user (login, password, role) VALUES (:login, :password, :role);');
|
||||
$req->execute(['login' => $user->getLogin(), 'password' => $user->getPasswordHash(), 'role' => $user->getRole()]);
|
||||
try {
|
||||
$req->execute(['login' => $user->getLogin(), 'password' => $user->getPasswordHash(), 'role' => $user->getRole()]);
|
||||
} catch (PDOException $ex) {
|
||||
if (UniqueViolation::isUniqueViolation($ex)) {
|
||||
return false;
|
||||
}
|
||||
throw $ex;
|
||||
}
|
||||
$user->setId(intval($this->pdo->lastInsertId()));
|
||||
return true;
|
||||
}
|
||||
|
@@ -1,6 +1,6 @@
|
||||
CREATE TABLE registered_user (
|
||||
id_user SERIAL PRIMARY KEY,
|
||||
login VARCHAR(32) NOT NULL,
|
||||
login VARCHAR(32) NOT NULL UNIQUE,
|
||||
password CHAR(72) NOT NULL, -- BCrypt
|
||||
role INT NOT NULL DEFAULT 0
|
||||
);
|
||||
@@ -25,4 +25,4 @@ CREATE TABLE comment (
|
||||
ON DELETE CASCADE,
|
||||
FOREIGN KEY (author_id) REFERENCES registered_user(id_user)
|
||||
ON DELETE CASCADE
|
||||
);
|
||||
);
|
||||
|
Reference in New Issue
Block a user