80 lines
2.4 KiB
PHP
Executable File
80 lines
2.4 KiB
PHP
Executable File
<?php
|
|
namespace app\core;
|
|
|
|
use app\exceptions\InvalidAuthTokenException;
|
|
use app\exceptions\InvalidBodyException;
|
|
use app\exceptions\InvalidRequestException;
|
|
use app\exceptions\InvalidAuthRequestException;
|
|
|
|
use app\models\LoginModel;
|
|
use app\models\RegisterModel;
|
|
use Exception;
|
|
|
|
class Controller
|
|
{
|
|
private string $method;
|
|
private ?array $body;
|
|
private ?string $token;
|
|
private ?string $authRequest;
|
|
|
|
public function __construct(string $method, ?string $authRequest, ?array $body, ?string $token)
|
|
{
|
|
$this->method = $method;
|
|
$this->body = $body;
|
|
$this->authRequest = $authRequest;
|
|
$this->token = $token;
|
|
}
|
|
|
|
public function run(): void
|
|
{
|
|
try {
|
|
if (!$this->isTokenValid()) throw new InvalidAuthTokenException();
|
|
if (!$this->isAuthRequestValid()) throw new InvalidAuthRequestException();
|
|
if (!$this->body) throw new InvalidBodyException();
|
|
|
|
$model = match ($this->method) {
|
|
'GET' => new LoginModel(),
|
|
'PUT' => new RegisterModel(),
|
|
default => throw new InvalidRequestException(),
|
|
};
|
|
|
|
$model->createConnection();
|
|
$result = $model->executeReq($this->body);
|
|
|
|
$this->writeResponse(
|
|
DVC::getHttpCodeWithCode(DVC::$successReturnCode),
|
|
DVC::$successReturnCode, $result
|
|
);
|
|
|
|
} catch (Exception $e){
|
|
$this->writeResponse(DVC::getHttpCodeWithCode($e->getCode()),
|
|
$e->getCode(), $e->getMessage()
|
|
);
|
|
}
|
|
}
|
|
|
|
private function isTokenValid(): bool
|
|
{
|
|
$validToken = hash('md5', 'service_authentication');
|
|
return $validToken === $this->token;
|
|
}
|
|
|
|
private function isAuthRequestValid(): bool
|
|
{
|
|
return match ($this->authRequest){
|
|
"register", "login" => true,
|
|
default => false
|
|
};
|
|
}
|
|
|
|
private function writeResponse(int $httpCode, int $returnCode, string|array $returnMessage): void
|
|
{
|
|
header("Content-Disposition: ".DVC::$nameOfResponsePackage);
|
|
header("Content-Type: application/json");
|
|
http_response_code($httpCode);
|
|
echo json_encode([
|
|
"code" => $returnCode,
|
|
"message" => $returnMessage
|
|
]);
|
|
}
|
|
} |