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
|
private function getPDO(): PDO
|
||||||
{
|
{
|
||||||
if ($this->pdo === null) {
|
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;
|
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;
|
namespace Silex\Gateway;
|
||||||
|
|
||||||
use PDO;
|
use PDO;
|
||||||
|
use PDOException;
|
||||||
use Silex\Model\User;
|
use Silex\Model\User;
|
||||||
|
|
||||||
class UserGateway
|
class UserGateway
|
||||||
@@ -37,7 +38,14 @@ class UserGateway
|
|||||||
public function insert(User $user): bool
|
public function insert(User $user): bool
|
||||||
{
|
{
|
||||||
$req = $this->pdo->prepare('INSERT INTO registered_user (login, password, role) VALUES (:login, :password, :role);');
|
$req = $this->pdo->prepare('INSERT INTO registered_user (login, password, role) VALUES (:login, :password, :role);');
|
||||||
|
try {
|
||||||
$req->execute(['login' => $user->getLogin(), 'password' => $user->getPasswordHash(), 'role' => $user->getRole()]);
|
$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()));
|
$user->setId(intval($this->pdo->lastInsertId()));
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
CREATE TABLE registered_user (
|
CREATE TABLE registered_user (
|
||||||
id_user SERIAL PRIMARY KEY,
|
id_user SERIAL PRIMARY KEY,
|
||||||
login VARCHAR(32) NOT NULL,
|
login VARCHAR(32) NOT NULL UNIQUE,
|
||||||
password CHAR(72) NOT NULL, -- BCrypt
|
password CHAR(72) NOT NULL, -- BCrypt
|
||||||
role INT NOT NULL DEFAULT 0
|
role INT NOT NULL DEFAULT 0
|
||||||
);
|
);
|
||||||
|
Reference in New Issue
Block a user