Files

119 lines
3.4 KiB
PHP
Executable File

<?php
namespace app\core;
use app\external_requests\CurlRequestBuilder;
abstract class Model{
public const RULE_REQUIRED = 'required';
public const RULE_EMAIL = 'email';
public array $errors = array();
private ?string $request = NULL;
private string $url = "192.168.0.13:701/authentication";
private ?array $headers = [];
private ?array $body = [];
private ?int $code = NULL;
private ?string $message = NULL;
public function loadData($data): void
{
foreach ($data as $key => $value){
if(property_exists($this, $key)){
$this->{$key} = $value;
}
}
}
abstract public function rules(): array;
public abstract function labels(): array;
public function errorMessages(): array{
return [
self::RULE_REQUIRED => 'This field is required',
self::RULE_EMAIL => 'This field must be a valid email address',
];
}
public function checkForErrors(): void{
foreach($this->rules() as $field => $rules){
$value = $this->{$field};
foreach ($rules as $rule){
if($rule == self::RULE_REQUIRED && !strlen($value)) {
$this->addError($field, $this->errorMessages()[$rule]);
break;
}
if($rule == self::RULE_EMAIL && !filter_var($value, FILTER_VALIDATE_EMAIL)) {
$this->addError($field, $this->errorMessages()[$rule]);
break;
}
}
}
}
protected abstract function createBody(): array;
protected abstract function createHeaders(string $body): array;
protected abstract function formatHeaderArray(array $headers): array;
public function setParametersForRequest(string $request, array $headers, array $body): void
{
$this->request = $request;
$this->headers = $headers;
$this->body = $body;
}
public function execute(): void
{
$requestBuilder = new CurlRequestBuilder();
$requestBuilder->setRequest($this->request);
$requestBuilder->setUrl($this->url);
$requestBuilder->setHeaders($this->headers);
$requestBuilder->setBody($this->body);
$requestBuilder->setIsReturnable(true);
$curl = $requestBuilder->getCurlRequestObject();
$response = json_decode($curl->makeRequest(), true);
$this->code = $response["code"];
$this->message = $response["message"];
}
public function isRequestFulfilled(): bool
{
return $this->code == DVC::$successReturnCode;
}
public function setRequestError(): void
{
Application::$app->view->setActionError($this->message);
}
public function addError($attribute, $message): void
{
$this->errors[$attribute] = $message;
}
public function removeErrors(): void
{
unset($this->errors);
$this->errors = array();
}
public function hasErrors(): bool
{
return count($this->errors);
}
public function getError($field): ?string
{
return array_key_exists($field, $this->errors) ? $this->errors[$field] : NULL;
}
public function getValueForField($field):string
{
return $this->{$field};
}
}