From d927550d8be027cd16c1e78bfddc797638d18ae7 Mon Sep 17 00:00:00 2001 From: clfreville2 Date: Wed, 30 Nov 2022 11:42:16 +0100 Subject: [PATCH] =?UTF-8?q?G=C3=A8re=20le=20cas=20o=C3=B9=20le=20login=20e?= =?UTF-8?q?st=20d=C3=A9j=C3=A0=20pris=20=C3=A0=20l'inscription?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Silex/DI/DI.php | 3 ++- src/Silex/Gateway/UniqueViolation.php | 15 +++++++++++++++ src/Silex/Gateway/UserGateway.php | 10 +++++++++- tables.sql | 4 ++-- 4 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 src/Silex/Gateway/UniqueViolation.php diff --git a/src/Silex/DI/DI.php b/src/Silex/DI/DI.php index abb1a9b..f4ab35b 100644 --- a/src/Silex/DI/DI.php +++ b/src/Silex/DI/DI.php @@ -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; } diff --git a/src/Silex/Gateway/UniqueViolation.php b/src/Silex/Gateway/UniqueViolation.php new file mode 100644 index 0000000..df444d5 --- /dev/null +++ b/src/Silex/Gateway/UniqueViolation.php @@ -0,0 +1,15 @@ +errorInfo[1] === 1062; // Mysql + } +} diff --git a/src/Silex/Gateway/UserGateway.php b/src/Silex/Gateway/UserGateway.php index 0467f21..34a9b57 100644 --- a/src/Silex/Gateway/UserGateway.php +++ b/src/Silex/Gateway/UserGateway.php @@ -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; } diff --git a/tables.sql b/tables.sql index 6f03838..5678201 100644 --- a/tables.sql +++ b/tables.sql @@ -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 -); \ No newline at end of file +);