ringfinger/backend/classes/core/AbstractController.php

120 lines
2.6 KiB
PHP
Raw Permalink Normal View History

2020-08-17 23:46:58 +02:00
<?php
declare(strict_types=1);
abstract class AbstractController
{
2020-08-23 12:37:39 +02:00
protected string $route;
protected ApiResponse $response;
protected Session $session;
protected string $requestUrl;
protected ?string $requestBody = null;
protected ?object $jsonBody = null;
2020-08-23 12:37:39 +02:00
protected ?string $contentType = null;
/** @var string[] */
2020-08-23 12:37:39 +02:00
protected array $mandatoryAttributes = [];
public function __construct(string $url)
{
$this->requestUrl = $url;
$this->response = new ApiResponse();
$this->session = new Session();
}
public function setRequestBody(string $contentType, string $content): void
{
$this->requestBody = $content;
$this->contentType = $contentType;
}
public function getResponse(): ApiResponse
{
return $this->response;
}
public function handle(): void
{
if (!$this->validateJsonBody()) {
$this->response = new ApiJsonResponse(ServerStatus::BAD_REQUEST);
$this->response->setSuccess(false);
2020-08-23 12:37:39 +02:00
$this->response->setMessage('The request body has not the required json attributes!');
}
}
protected function getUrlParam(string $name): ?string
{
foreach (explode('/', $this->route) as $index => $fragment) {
if ($fragment === '{' . $name . '}') {
return explode('/', $this->requestUrl)[$index];
}
}
return null;
}
protected function getUrlParamInt(string $name): ?int
{
$param = $this->getUrlParam($name);
return $param !== null ? (int)$param : null;
}
public function isUserLoggedIn(): bool
2020-08-22 23:08:05 +02:00
{
if (!$this->session->IsLoggedIn()) {
$this->response = new ApiJsonResponse(ServerStatus::UNAUTHORIZED);
$this->response->setParameter('success', false);
$this->response->setMessage('You are not logged in!');
return false;
}
return true;
}
2020-08-23 12:37:39 +02:00
public function hasUserPermission(int $userId): bool
2020-08-22 23:08:05 +02:00
{
$this->response = new ApiJsonResponse();
$hasPermission = $this->session->isAdmin() || $this->session->getUserId() === $userId;
if (!$hasPermission) {
$this->response->setSuccess(false);
$this->response->setMessage('You don\'t have the permission!');
2020-08-22 23:08:05 +02:00
$this->response->setStatus(ServerStatus::UNAUTHORIZED);
}
return $hasPermission;
}
2020-08-23 12:37:39 +02:00
protected function validateJsonBody(): bool
{
if (count($this->mandatoryAttributes) === 0) {
return true;
}
if ($this->contentType === MimeType::JSON && $this->requestBody === null) {
return false;
}
try {
$json = json_decode($this->requestBody);
foreach ($this->mandatoryAttributes as $attribute) {
if (!isset($json->{$attribute})) {
return false;
}
}
$this->jsonBody = $json;
2020-08-23 12:37:39 +02:00
return true;
} catch (Throwable $e) {
return false;
}
}
2020-08-17 23:46:58 +02:00
}