hydra-sql/src/Service/SQLLoginService.php

92 lines
3.1 KiB
PHP

<?php
namespace App\Service;
use App\SQLLogin\Exception\DatabaseConnectionException;
use App\SQLLogin\Exception\DataToFetchConfigurationException;
use App\SQLLogin\Exception\LoginElementsConfigurationException;
use App\SQLLogin\Exception\NullDataToFetchException;
use App\SQLLogin\SQLLoginConnect;
use App\SQLLogin\SQLLoginRequest;
use PDO;
use PDOException;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class SQLLoginService extends AbstractController
{
public SQLLoginRequest $sqlLoginRequest;
public function __construct(SQLLoginRequest $sqlLoginRequest, private LoggerInterface $loggerInterface)
{
$this->sqlLoginRequest = $sqlLoginRequest;
$this->loggerInterface = $loggerInterface;
}
public function fetchDatas($login): array
{
try {
$dbh = $this->getConnection();
} catch (PDOException $e) {
$this->loggerInterface->critical($e->getMessage());
throw new DatabaseConnectionException($e->getMessage());
}
try {
// forge de la requête
$request = $this->sqlLoginRequest->getRequestScope();
} catch (NullDataToFetchException $e) {
throw new DataToFetchConfigurationException($e->getMessage());
}
try {
// Préparation de la requête
$query = $dbh->prepare($request);
$query->execute([$this->sqlLoginRequest->getLoginColumnName() => $login]);
$datas = $query->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$this->loggerInterface->critical($e->getMessage());
throw new DataToFetchConfigurationException($e->getMessage());
}
return $datas;
}
public function fetchPassword($login): array|bool
{
try {
$dbh = $this->getConnection();
} catch (PDOException $e) {
$this->loggerInterface->critical($e->getMessage());
throw new DatabaseConnectionException($e->getMessage());
}
// forge de la requête
$request = $this->sqlLoginRequest->getRequestPassword();
try {
$query = $dbh->prepare($request);
$query->execute([$this->sqlLoginRequest->getLoginColumnName() => $login]);
$password = $query->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$this->loggerInterface->critical($e->getMessage());
throw new LoginElementsConfigurationException($e->getMessage());
}
if ($password) {
return [
$password[$this->sqlLoginRequest->getPasswordColumnName()],
isset($password[$this->sqlLoginRequest->getSaltColumnName()]) ? $password[$this->sqlLoginRequest->getSaltColumnName()] : null,
];
}
return false;
}
public function getConnection(): PDO
{
// Appel du singleton
$sqlLogin = SQLLoginConnect::getInstance();
// Connection bdd
return $sqlLogin->connect($this->sqlLoginRequest->getDatabaseDsn(), $this->sqlLoginRequest->getDbUser(), $this->sqlLoginRequest->getDbPassword());
}
}