microserviciile de register, login finalizate
This commit is contained in:
Regular → Executable
+41
-92
@@ -1,93 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
use app\core\exceptions\ForbiddenException;
|
||||
use app\core\exceptions\NotFoundException;
|
||||
|
||||
class Application
|
||||
{
|
||||
public static string $ROOT_DIR;
|
||||
public string $userClass;
|
||||
public string $layout = 'main';
|
||||
|
||||
public Router $router;
|
||||
public Request $request;
|
||||
public Response $response;
|
||||
public static Application $app;
|
||||
public ?Controller $controller = null;
|
||||
public Database $db;
|
||||
public Session $session;
|
||||
public ?DbModel $user;
|
||||
public View $view;
|
||||
|
||||
public function __construct($rootPath, array $config)
|
||||
{
|
||||
self::$ROOT_DIR = $rootPath;
|
||||
$this->userClass = $config['userClass'];
|
||||
self::$app = $this;
|
||||
|
||||
$this->request = new Request();
|
||||
$this->response = new Response();
|
||||
$this->router = new Router($this->request, $this->response);
|
||||
$this->view = new View();
|
||||
|
||||
$this->db = new Database($config['db']);
|
||||
$this->session = new Session();
|
||||
|
||||
$primaryValue = $this->session->get('user');
|
||||
if ($primaryValue) {
|
||||
$userObj = new $this->userClass();
|
||||
$primaryKey = $userObj->primaryKey();
|
||||
$this->user = $userObj->findOne([$primaryKey => $primaryValue]);
|
||||
} else {
|
||||
$this->user = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function setController($controller)
|
||||
{
|
||||
$this->controller = $controller;
|
||||
}
|
||||
|
||||
public function getController()
|
||||
{
|
||||
return $this->controller;
|
||||
}
|
||||
|
||||
public function login(DbModel $user)
|
||||
{
|
||||
$this->user = $user;
|
||||
$primaryKey = $user->primaryKey();
|
||||
$primaryValue = $user->{$primaryKey};
|
||||
$this->session->set('user', $primaryValue);
|
||||
return true;
|
||||
}
|
||||
|
||||
public function logout()
|
||||
{
|
||||
$this->user = null;
|
||||
$this->session->remove('user');
|
||||
}
|
||||
|
||||
public static function isLoggedIn()
|
||||
{
|
||||
return !self::$app->user;
|
||||
}
|
||||
|
||||
public function run()
|
||||
{
|
||||
try{
|
||||
echo $this->router->resolve();
|
||||
}catch(ForbiddenException $e){
|
||||
$this->response->setStatusCode(403);
|
||||
echo $this->view->renderView('_error', [
|
||||
'exception' => $e
|
||||
]);
|
||||
}catch(NotFoundException $e){
|
||||
$this->response->setStatusCode(404);
|
||||
echo $this->view->renderView('_error', [
|
||||
'exception' => $e
|
||||
]);
|
||||
}
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
use AllowDynamicProperties;
|
||||
use app\exceptions\ForbiddenAccessException;
|
||||
use app\exceptions\PageNotFoundException;
|
||||
|
||||
#[AllowDynamicProperties] class Application
|
||||
{
|
||||
public static string $ROOT_DIR;
|
||||
|
||||
public static Application $app;
|
||||
public Router $router;
|
||||
public Request $request;
|
||||
public Response $response;
|
||||
public ?Controller $controller = null;
|
||||
public Session $session;
|
||||
public View $view;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
self::$ROOT_DIR = dirname(__DIR__);
|
||||
self::$app = $this;
|
||||
$this->request = new Request();
|
||||
$this->response = new Response();
|
||||
$this->router = new Router($this->request);
|
||||
$this->view = new View();
|
||||
$this->session = new Session();
|
||||
}
|
||||
|
||||
public function run(): void
|
||||
{
|
||||
try{
|
||||
echo $this->router->resolve();
|
||||
}catch(ForbiddenAccessException $e){
|
||||
|
||||
}catch(PageNotFoundException $e){
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
Regular → Executable
+25
-25
@@ -1,26 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
use app\core\middlewares\BaseMiddleware;
|
||||
|
||||
class Controller{
|
||||
public string $layout = 'main';
|
||||
public string $action = '';
|
||||
protected array $middlewares = [];
|
||||
|
||||
public function render($view, $params = []){
|
||||
return Application::$app->view->renderView($view, $params);
|
||||
}
|
||||
|
||||
public function setLayout($layout){
|
||||
$this->layout = $layout;
|
||||
}
|
||||
|
||||
public function registerMiddleware(BaseMiddleware $middleware){
|
||||
$this->middlewares[] = $middleware;
|
||||
}
|
||||
|
||||
public function getMiddlewares(){
|
||||
return $this->middlewares;
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
abstract class Controller{
|
||||
protected string $view = "";
|
||||
protected string $title = "";
|
||||
protected string $layout = "";
|
||||
protected ?Model $model = NULL;
|
||||
public function render(): string
|
||||
{
|
||||
Application::$app->view->setLayout($this->layout);
|
||||
Application::$app->view->setTitle($this->title);
|
||||
Application::$app->view->setView($this->view);
|
||||
Application::$app->view->setModel($this->model);
|
||||
|
||||
return Application::$app->view->render();
|
||||
}
|
||||
|
||||
protected static abstract function setControllerParams(string $title, string $view, string $layout, ?Model $model);
|
||||
|
||||
public function setView(string $view): void {$this->view = $view;}
|
||||
public function setTitle(string $title): void {$this->title = $title;}
|
||||
public function setLayout(string $layout): void {$this->layout = $layout;}
|
||||
public function setModel(?Model $model): void {$this->model = $model;}
|
||||
}
|
||||
Executable
+96
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
Class DVC
|
||||
{
|
||||
public static string $nameOfResponsePackage = "response_package";
|
||||
|
||||
public static string $successName = "Success";
|
||||
public static string $genericExceptionName = "GenericErrorException";
|
||||
public static string $invalidTokenName = "InvalidTokenException";
|
||||
public static string $invalidRequestName = "InvalidRequestException";
|
||||
public static string $invalidCurlStructureName = "InvalidCurlStructureException";
|
||||
public static string $invalidBodyName = "InvalidBodyException";
|
||||
public static string $alreadyExistsName = "AlreadyExistsException";
|
||||
public static string $userNotExistingName = "userNotExistingException";
|
||||
public static string $fieldNotExistingName = "FieldNotExistingException";
|
||||
public static string $pageNotFoundName = "pageNotfoundException";
|
||||
public static string $forbiddenAccessName = "forbiddenAccessException";
|
||||
public static string $serviceNotFoundName = "FieldNotFoundException";
|
||||
|
||||
public static string $returnCode = "returnCode";
|
||||
public static string $returnMessage = "returnMessage";
|
||||
|
||||
public static int $successReturnCode = 460;
|
||||
|
||||
public static function getArrayResponse(string $name): array
|
||||
{
|
||||
return match ($name){
|
||||
DVC::$successName => [
|
||||
DVC::$returnCode => 460,
|
||||
DVC::$returnMessage => "Operation done successfully"
|
||||
],
|
||||
DVC::$genericExceptionName => [
|
||||
DVC::$returnCode => 461,
|
||||
DVC::$returnMessage => "Internal Server Error"
|
||||
],
|
||||
DVC::$invalidTokenName => [
|
||||
DVC::$returnCode => 462,
|
||||
DVC::$returnMessage => "Unauthorized access"
|
||||
],
|
||||
DVC::$invalidRequestName => [
|
||||
DVC::$returnCode => 463,
|
||||
DVC::$returnMessage => "Service doesn't provide this type of request"
|
||||
],
|
||||
DVC::$invalidBodyName => [
|
||||
DVC::$returnCode => 464,
|
||||
DVC::$returnMessage => "Not valid parameters sent"
|
||||
],
|
||||
DVC::$alreadyExistsName => [
|
||||
|
||||
DVC::$returnCode => 465,
|
||||
DVC::$returnMessage => "Field already existing"
|
||||
],
|
||||
DVC::$fieldNotExistingName => [
|
||||
DVC::$returnCode => 466,
|
||||
DVC::$returnMessage => "Field not existing anymore"
|
||||
],
|
||||
DVC::$invalidCurlStructureName => [
|
||||
DVC::$returnCode => 467,
|
||||
DVC::$returnMessage => "cURL class needs URL, request method and headers to run"
|
||||
],
|
||||
DVC::$userNotExistingName => [
|
||||
DVC::$returnCode => 468,
|
||||
DVC::$returnMessage => "User account doesn't exists"
|
||||
],
|
||||
DVC::$pageNotFoundName => [
|
||||
DVC::$returnCode => 469,
|
||||
DVC::$returnMessage => "Page not found"
|
||||
],
|
||||
DVC::$forbiddenAccessName => [
|
||||
DVC::$returnCode => 470,
|
||||
DVC::$returnMessage => "You are not authorised to access this page"
|
||||
],
|
||||
DVC::$serviceNotFoundName => [
|
||||
DVC::$returnCode => 471,
|
||||
DVC::$returnCode => "Service not existing"
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
public static function getHttpCodeWithCode(int $code): int
|
||||
{
|
||||
return match ($code){
|
||||
460 => 200,
|
||||
461 => 500,
|
||||
462 => 401,
|
||||
463 => 405,
|
||||
464 => 400,
|
||||
465, 466 => 204,
|
||||
467 => 409,
|
||||
468, 469, 471 => 404,
|
||||
470 => 403,
|
||||
default => 100
|
||||
};
|
||||
}
|
||||
}
|
||||
Regular → Executable
+77
-77
@@ -1,78 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class Database{
|
||||
public \PDO $pdo;
|
||||
|
||||
public function __construct(array $config){
|
||||
$dsn = $config['dsn'] ?? '';
|
||||
$user = $config['user'] ?? '';
|
||||
$password = $config['password'] ?? '';
|
||||
$this->pdo = new \PDO($dsn, $user, $password);
|
||||
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
||||
}
|
||||
|
||||
public function applyMigrations(){
|
||||
$this->createMigrationsTable();
|
||||
$appliedMigrations = $this->getAppliedMigrations();
|
||||
|
||||
$newMigrations = [];
|
||||
$files = scandir(Application::$ROOT_DIR.'/migrations');
|
||||
$toApplyMigrations = array_diff($files, $appliedMigrations);
|
||||
|
||||
foreach($toApplyMigrations as $migration){
|
||||
if($migration === '.' || $migration === '..'){
|
||||
continue;
|
||||
}
|
||||
|
||||
require_once Application::$ROOT_DIR.'/migrations/'.$migration;
|
||||
$className = pathinfo($migration, PATHINFO_FILENAME);
|
||||
|
||||
$instance = new $className();
|
||||
$this->log("Applying migration $migration" . PHP_EOL);
|
||||
$instance->up();
|
||||
$this->log("Applied migration $migration" . PHP_EOL);
|
||||
|
||||
$newMigrations[] = $migration;
|
||||
}
|
||||
|
||||
if(!empty($newMigrations)){
|
||||
$this->saveMigrations($newMigrations);
|
||||
}else{
|
||||
$this->log('All migrations are applied');
|
||||
}
|
||||
}
|
||||
|
||||
public function createMigrationsTable(){
|
||||
$this->pdo->exec("
|
||||
CREATE TABLE IF NOT EXISTS migrations (
|
||||
id INT AUTO_INCREMENT,
|
||||
migration varchar(255),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id)
|
||||
)
|
||||
ENGINE=INNODB;");
|
||||
}
|
||||
|
||||
public function getAppliedMigrations(){
|
||||
$statement = $this->pdo->prepare("SELECT migration FROM migrations");
|
||||
$statement->execute();
|
||||
|
||||
return $statement->fetchAll(\PDO::FETCH_COLUMN);
|
||||
}
|
||||
|
||||
public function saveMigrations(array $migrations){
|
||||
$str = implode(",", array_map(fn($m) => "('$m')", $migrations));
|
||||
$statement = $this->pdo->prepare("INSERT INTO migrations (migration) VALUES $str");
|
||||
$statement->execute();
|
||||
}
|
||||
|
||||
public function prepare($sql){
|
||||
return $this->pdo->prepare($sql);
|
||||
}
|
||||
|
||||
protected function log($message){
|
||||
echo '['.date('Y-m-d H:i:s').'] - '.$message.PHP_EOL;
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class Database{
|
||||
public \PDO $pdo;
|
||||
|
||||
public function __construct(array $config){
|
||||
$dsn = $config['dsn'] ?? '';
|
||||
$user = $config['user'] ?? '';
|
||||
$password = $config['password'] ?? '';
|
||||
$this->pdo = new \PDO($dsn, $user, $password);
|
||||
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
||||
}
|
||||
|
||||
public function applyMigrations(){
|
||||
$this->createMigrationsTable();
|
||||
$appliedMigrations = $this->getAppliedMigrations();
|
||||
|
||||
$newMigrations = [];
|
||||
$files = scandir(Application::$ROOT_DIR.'/migrations');
|
||||
$toApplyMigrations = array_diff($files, $appliedMigrations);
|
||||
|
||||
foreach($toApplyMigrations as $migration){
|
||||
if($migration === '.' || $migration === '..'){
|
||||
continue;
|
||||
}
|
||||
|
||||
require_once Application::$ROOT_DIR.'/migrations/'.$migration;
|
||||
$className = pathinfo($migration, PATHINFO_FILENAME);
|
||||
|
||||
$instance = new $className();
|
||||
$this->log("Applying migration $migration" . PHP_EOL);
|
||||
$instance->up();
|
||||
$this->log("Applied migration $migration" . PHP_EOL);
|
||||
|
||||
$newMigrations[] = $migration;
|
||||
}
|
||||
|
||||
if(!empty($newMigrations)){
|
||||
$this->saveMigrations($newMigrations);
|
||||
}else{
|
||||
$this->log('All migrations are applied');
|
||||
}
|
||||
}
|
||||
|
||||
public function createMigrationsTable(){
|
||||
$this->pdo->exec("
|
||||
CREATE TABLE IF NOT EXISTS migrations (
|
||||
id INT AUTO_INCREMENT,
|
||||
migration varchar(255),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (id)
|
||||
)
|
||||
ENGINE=INNODB;");
|
||||
}
|
||||
|
||||
public function getAppliedMigrations(){
|
||||
$statement = $this->pdo->prepare("SELECT migration FROM migrations");
|
||||
$statement->execute();
|
||||
|
||||
return $statement->fetchAll(\PDO::FETCH_COLUMN);
|
||||
}
|
||||
|
||||
public function saveMigrations(array $migrations){
|
||||
$str = implode(",", array_map(fn($m) => "('$m')", $migrations));
|
||||
$statement = $this->pdo->prepare("INSERT INTO migrations (migration) VALUES $str");
|
||||
$statement->execute();
|
||||
}
|
||||
|
||||
public function prepare($sql){
|
||||
return $this->pdo->prepare($sql);
|
||||
}
|
||||
|
||||
protected function log($message){
|
||||
echo '['.date('Y-m-d H:i:s').'] - '.$message.PHP_EOL;
|
||||
}
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
abstract class DbModel extends Model{
|
||||
abstract public function tableName(): string;
|
||||
|
||||
abstract public function attributes(): array;
|
||||
|
||||
abstract public function primaryKey(): string;
|
||||
|
||||
public function save(){
|
||||
$tableName = $this->tableName();
|
||||
$attributes = $this->attributes();
|
||||
$params = array_map(fn($attr) => ":$attr", $attributes);
|
||||
|
||||
$statement = self::prepare("INSERT INTO $tableName ("
|
||||
.implode(',', $attributes)
|
||||
.") VALUES ("
|
||||
.implode(',', $params)
|
||||
.")"
|
||||
);
|
||||
|
||||
foreach($attributes as $attribute){
|
||||
$statement->bindValue(":$attribute", $this->{$attribute});
|
||||
}
|
||||
|
||||
$statement->execute();
|
||||
return true;
|
||||
}
|
||||
|
||||
public static function prepare($sql){
|
||||
return Application::$app->db->pdo->prepare($sql);
|
||||
}
|
||||
|
||||
public function findOne($where){
|
||||
$tableName = static::tableName();
|
||||
$attributes = array_keys($where);
|
||||
|
||||
$sql = implode("AND ", array_map(fn($attr) => "$attr = :$attr", $attributes));
|
||||
$statement = self::prepare("SELECT * from $tableName WHERE $sql");
|
||||
|
||||
foreach($where as $key => $item){
|
||||
$statement->bindValue(":$key", $item);
|
||||
}
|
||||
|
||||
$statement->execute();
|
||||
|
||||
return $statement->fetchObject(static::class);
|
||||
}
|
||||
}
|
||||
Regular → Executable
+118
-103
@@ -1,104 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
abstract class Model{
|
||||
public const RULE_REQUIRED = 'required';
|
||||
public const RULE_EMAIL = 'email';
|
||||
public const RULE_MIN = 'min';
|
||||
public const RULE_MAX = 'max';
|
||||
public const RULE_UNIQUE = 'unique';
|
||||
|
||||
public function loadData($data){
|
||||
foreach ($data as $key => $value){
|
||||
if(property_exists($this, $key)){
|
||||
$this->{$key} = $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
abstract public function rules():array;
|
||||
|
||||
public function labels(): array{
|
||||
return [];
|
||||
}
|
||||
|
||||
public array $errors = [];
|
||||
|
||||
private function addErrorForRule(string $attribute, string $rule, $params =[]){
|
||||
$message = $this->errorMessages()[$rule] ?? '';
|
||||
foreach($params as $key => $value){
|
||||
$message = str_replace("{{$key}}", $value, $message);
|
||||
}
|
||||
|
||||
$this->errors[$attribute][] = $message;
|
||||
}
|
||||
|
||||
public function addError(string $attribute, string $message){
|
||||
$this->errors[$attribute][] = $message;
|
||||
}
|
||||
|
||||
public function errorMessages(){
|
||||
return [
|
||||
self::RULE_REQUIRED => 'This field is required',
|
||||
self::RULE_EMAIL => 'This field must be valid email address',
|
||||
self::RULE_MIN => 'Min length of this field must be {min}',
|
||||
self::RULE_MAX => 'Max length of this field must be {max}',
|
||||
self::RULE_UNIQUE => 'Email already exists'
|
||||
];
|
||||
}
|
||||
|
||||
public function validate(){
|
||||
foreach($this->rules() as $attribute => $rules){
|
||||
$value = $this->{$attribute};
|
||||
foreach($rules as $rule){
|
||||
$ruleName = $rule;
|
||||
|
||||
if(!is_string($ruleName)){
|
||||
$ruleName = $rule[0];
|
||||
}
|
||||
|
||||
if($ruleName === self::RULE_REQUIRED && !$value){
|
||||
$this->addErrorForRule($attribute, self::RULE_REQUIRED);
|
||||
}
|
||||
|
||||
if($ruleName === self::RULE_EMAIL && !filter_var($value, FILTER_VALIDATE_EMAIL)){
|
||||
$this->addErrorForRule($attribute, self::RULE_EMAIL);
|
||||
}
|
||||
|
||||
if($ruleName === self::RULE_MIN && strlen($value) < $rule['min']){
|
||||
$this->addErrorForRule($attribute, self::RULE_MIN, $rule);
|
||||
}
|
||||
|
||||
if($ruleName === self::RULE_MAX && strlen($value) > $rule['max']){
|
||||
$this->addErrorForRule($attribute, self::RULE_MAX, $rule);
|
||||
}
|
||||
|
||||
if($ruleName === self::RULE_UNIQUE){
|
||||
$className = $rule['class'];
|
||||
$uniqueAttr = $rule['attirubute'] ?? $attribute;
|
||||
$tableName = $className::tableName();
|
||||
|
||||
$statement = Application::$app->db->prepare(("SELECT * FROM $tableName WHERE $uniqueAttr = :attr"));
|
||||
$statement->bindValue(":attr", $value);
|
||||
$statement->execute();
|
||||
$record = $statement->fetchObject();
|
||||
|
||||
if($record){
|
||||
$this->addErrorForRule($attribute, SELF::RULE_UNIQUE);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return empty($this->errors);
|
||||
}
|
||||
|
||||
public function hasError($attribute){
|
||||
return $this->errors[$attribute] ?? false;
|
||||
}
|
||||
|
||||
public function getFirstError($attribute){
|
||||
return $this->errors[$attribute][0] ?? '';
|
||||
}
|
||||
<?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};
|
||||
}
|
||||
}
|
||||
Regular → Executable
+53
-53
@@ -1,54 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class Request{
|
||||
private int $lengthOfRoot;
|
||||
|
||||
public function __construct(){
|
||||
$this->lengthOfRoot = strlen('knowyourfood') + 1;
|
||||
}
|
||||
|
||||
public function getPath(){//identificam din URL pe pagina trebuie accesata
|
||||
$path = $_SERVER['REQUEST_URI'];
|
||||
$path = substr($path, $this->lengthOfRoot);
|
||||
|
||||
$position = strpos($path, '?');
|
||||
|
||||
if(!$position){
|
||||
return $path;
|
||||
}
|
||||
|
||||
return substr($path, 0, $position);
|
||||
}
|
||||
|
||||
public function method(){
|
||||
return strtolower($_SERVER['REQUEST_METHOD']);
|
||||
}
|
||||
|
||||
public function isGet(){
|
||||
return $this->method() === 'get';
|
||||
}
|
||||
|
||||
public function isPost(){
|
||||
return $this->method() === 'post';
|
||||
}
|
||||
|
||||
//bazat pe tipul de request, accesam tuplele key/value pentru a identifica body ul requestului
|
||||
public function getBody(){
|
||||
$body = [];
|
||||
if($this->method() === 'get'){
|
||||
foreach($_GET as $key => $value){
|
||||
$body[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
if($this->method() === 'post'){
|
||||
foreach($_POST as $key => $value){
|
||||
$body[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
return $body;
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class Request{
|
||||
public function __construct(){
|
||||
}
|
||||
|
||||
public function getPath(): string
|
||||
{
|
||||
return $_SERVER['REQUEST_URI'];
|
||||
}
|
||||
|
||||
public function method():string
|
||||
{
|
||||
return $_SERVER['REQUEST_METHOD'];
|
||||
}
|
||||
|
||||
public function isGet(): bool
|
||||
{
|
||||
return $_SERVER['REQUEST_METHOD'] === "GET";
|
||||
}
|
||||
|
||||
public function isPost(): bool
|
||||
{
|
||||
return $_SERVER['REQUEST_METHOD'] === "POST";
|
||||
}
|
||||
|
||||
public function getGETBody(): ?array
|
||||
{
|
||||
$body = [];
|
||||
|
||||
if($this->method() === 'GET'){
|
||||
foreach($_GET as $key => $value){
|
||||
$body[$key] = filter_input(INPUT_GET, $key, FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
return $body;
|
||||
}
|
||||
|
||||
public function getPOSTBody(): ?array
|
||||
{
|
||||
$body = [];
|
||||
|
||||
if($this->method() === 'POST'){
|
||||
foreach($_POST as $key => $value){
|
||||
$body[$key] = filter_input(INPUT_POST, $key, FILTER_SANITIZE_SPECIAL_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
return $body;
|
||||
}
|
||||
}
|
||||
Regular → Executable
+12
-12
@@ -1,13 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class Response{
|
||||
public function setStatusCode(int $code){
|
||||
http_response_code($code);
|
||||
}
|
||||
|
||||
public function redirect(string $url){
|
||||
header("Location: ".$url);
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class Response{
|
||||
public function setStatusCode(int $code){
|
||||
http_response_code($code);
|
||||
}
|
||||
|
||||
public function redirect(string $url){
|
||||
header("Location: ".$url);
|
||||
}
|
||||
}
|
||||
Regular → Executable
+47
-49
@@ -1,50 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
use app\core\exceptions\NotFoundException;
|
||||
|
||||
class Router
|
||||
{
|
||||
public Request $request;
|
||||
public Response $response;
|
||||
protected array $routes = [];
|
||||
|
||||
public function __construct(Request $request, Response $response)
|
||||
{
|
||||
$this->request = $request;
|
||||
$this->response = $response;
|
||||
}
|
||||
|
||||
public function get($path, $callback)
|
||||
{
|
||||
$this->routes['get'][$path] = $callback;
|
||||
}
|
||||
|
||||
public function post($path, $callback)
|
||||
{
|
||||
$this->routes['post'][$path] = $callback;
|
||||
}
|
||||
|
||||
public function resolve()
|
||||
{
|
||||
$path = $this->request->getPath();
|
||||
$method = $this->request->method();
|
||||
$callback = $this->routes[$method][$path] ?? false;
|
||||
|
||||
if (!$callback) {
|
||||
throw new NotFoundException();
|
||||
}
|
||||
|
||||
$controller = new $callback[0]();
|
||||
Application::$app->controller = $controller;
|
||||
$controller->action = $callback[1];
|
||||
$callback[0] = $controller;
|
||||
|
||||
foreach ($controller->getMiddlewares() as $middleware) {
|
||||
$middleware->execute();
|
||||
}
|
||||
|
||||
return call_user_func($callback, $this->request, $this->response);
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
use app\exceptions\PageNotFoundException;
|
||||
|
||||
class Router
|
||||
{
|
||||
public Request $request;
|
||||
protected array $routes = [];
|
||||
|
||||
public function __construct(Request $request)
|
||||
{
|
||||
$this->request = $request;
|
||||
}
|
||||
|
||||
public function get($path, $callback): void
|
||||
{
|
||||
$this->routes['GET'][$path] = $callback;
|
||||
}
|
||||
|
||||
public function post($path, $callback): void
|
||||
{
|
||||
$this->routes['POST'][$path] = $callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws PageNotFoundException
|
||||
*/
|
||||
public function resolve()
|
||||
{
|
||||
$path = $this->request->getPath();
|
||||
$method = $this->request->method();
|
||||
$callback = $this->routes[$method][$path] ?? false;
|
||||
|
||||
if (!$callback) {
|
||||
throw new PageNotFoundException();
|
||||
}
|
||||
|
||||
Application::$app->controller = new $callback[0]();
|
||||
|
||||
/*
|
||||
* TODO:
|
||||
* de adaugat aici middleware urile asociate unui controller
|
||||
*/
|
||||
|
||||
return call_user_func($callback, $this->request);
|
||||
}
|
||||
}
|
||||
Regular → Executable
+6
-47
@@ -1,48 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class Session{
|
||||
protected const FLASH_KEY = 'flash_messages';
|
||||
|
||||
public function __construct(){
|
||||
session_start();
|
||||
foreach($_SESSION[self::FLASH_KEY] as $key => &$flashMessage){
|
||||
$flashMessage['remove'] = 'true';
|
||||
}
|
||||
}
|
||||
|
||||
public function setFlash($key, $message){
|
||||
$_SESSION[self::FLASH_KEY][$key] = [
|
||||
'value' => $message,
|
||||
'remove' => 'false'
|
||||
];
|
||||
}
|
||||
|
||||
public function getFlash($key){
|
||||
return $_SESSION[self::FLASH_KEY][$key]['value'] ?? false;
|
||||
}
|
||||
|
||||
public function set($key, $value){
|
||||
$_SESSION[$key] = $value;
|
||||
}
|
||||
|
||||
public function get($key){
|
||||
return $_SESSION[$key];
|
||||
}
|
||||
|
||||
public function remove($key){
|
||||
unset($_SESSION[$key]);
|
||||
}
|
||||
|
||||
public function __destruct(){
|
||||
$flashMessages = $_SESSION[self::FLASH_KEY] ?? [];
|
||||
foreach($flashMessages as $key => &$flashMessage){
|
||||
if($flashMessage['remove'] == 'true'){
|
||||
unset($flashMessages[$key]);
|
||||
}
|
||||
}
|
||||
|
||||
$_SESSION[self::FLASH_KEY] = $flashMessages;
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class Session{
|
||||
|
||||
}
|
||||
Regular → Executable
+44
-44
@@ -1,45 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class View{
|
||||
public string $title = '';
|
||||
|
||||
protected function layoutContent()
|
||||
{
|
||||
$layout = Application::$app->layout;
|
||||
if (Application::$app->controller) {
|
||||
$layout = Application::$app->controller->layout;
|
||||
}
|
||||
|
||||
ob_start();
|
||||
include_once Application::$ROOT_DIR . "/views/layouts/$layout.php";
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
|
||||
public function renderView($view, $params = [])
|
||||
{
|
||||
$viewContent = $this->renderOnlyView($view, $params);
|
||||
$layoutContent = $this->layoutContent();
|
||||
|
||||
return str_replace('{{content}}', $viewContent, $layoutContent);
|
||||
}
|
||||
|
||||
public function renderContent($viewContent)
|
||||
{
|
||||
$layoutContent = $this->layoutContent();
|
||||
return str_replace('{{content}}', $viewContent, $layoutContent);
|
||||
}
|
||||
|
||||
protected function renderOnlyView($view, $params)
|
||||
{
|
||||
foreach ($params as $key => $value) {
|
||||
$$key = $value;
|
||||
}
|
||||
|
||||
ob_start();
|
||||
include_once Application::$ROOT_DIR."/views/$view.php";
|
||||
return ob_get_clean();
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core;
|
||||
|
||||
class View{
|
||||
private string $title = '';
|
||||
private string $view = '';
|
||||
private string $layout = 'main';
|
||||
private ?Model $model = NULL;
|
||||
private string $actionError = '';
|
||||
|
||||
public function render(): string
|
||||
{
|
||||
$viewContent = $this->renderView();
|
||||
$layoutContent = $this->renderLayout();
|
||||
|
||||
return str_replace('{{content}}', $viewContent, $layoutContent);
|
||||
}
|
||||
|
||||
public function renderView(): string
|
||||
{
|
||||
ob_start();
|
||||
include_once Application::$ROOT_DIR . "/views/$this->view.php";
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
public function renderLayout(): string
|
||||
{
|
||||
ob_start();
|
||||
include_once Application::$ROOT_DIR . "/views/layouts/HTML/$this->layout.php";
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
public function setLayout($layout): void {$this->layout = $layout;}
|
||||
public function setTitle($title): void {$this->title = $title;}
|
||||
public function setView($view): void {$this->view = $view;}
|
||||
public function setModel(?Model $model): void {$this->model = $model;}
|
||||
public function setActionError(string $actionError): void {$this->actionError = $actionError;}
|
||||
|
||||
public function getTitle(): string {return $this->title;}
|
||||
public function getView(): string {return $this->view;}
|
||||
public function getLayout(): string {return $this->layout;}
|
||||
public function getModel(): ?Model {return $this->model;}
|
||||
public function getActionError(): string {return $this->actionError;}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\exceptions;
|
||||
|
||||
class ForbiddenException extends \Exception{
|
||||
protected $code = 403;
|
||||
protected $message = 'You do not have permission to access this page';
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\exceptions;
|
||||
|
||||
class NotFoundException extends \Exception{
|
||||
protected $code = 404;
|
||||
protected $message = 'Page not found';
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
use app\core\Model;
|
||||
|
||||
abstract class BaseField
|
||||
{
|
||||
public Model $model;
|
||||
public string $attribute;
|
||||
|
||||
public function __construct(Model $model, string $attribute)
|
||||
{
|
||||
$this->model = $model;
|
||||
$this->attribute = $attribute;
|
||||
}
|
||||
|
||||
abstract public function renderInput(): string;
|
||||
|
||||
public function __toString()
|
||||
{
|
||||
return sprintf('
|
||||
<div class="mb-3">
|
||||
<label>%s</label>
|
||||
%s
|
||||
<div class="invalid-feedback">
|
||||
%s
|
||||
</div>
|
||||
</div>
|
||||
',
|
||||
$this->model->labels()[$this->attribute] ?? $this->attribute,
|
||||
$this->renderInput(),
|
||||
$this->model->getFirstError($this->attribute)
|
||||
);
|
||||
}
|
||||
}
|
||||
Regular → Executable
+11
-11
@@ -1,12 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
|
||||
class Button{
|
||||
public function __toString(){
|
||||
return sprintf('
|
||||
<button type="submit" class="button">Submit</button>
|
||||
',
|
||||
);
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
|
||||
class Button{
|
||||
public function __toString(){
|
||||
return sprintf('
|
||||
<button type="submit" class="button">Submit</button>
|
||||
',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
use app\core\Model;
|
||||
|
||||
class Field{
|
||||
public const TYPE_TEXT = 'text';
|
||||
public const TYPE_PASSWORD = 'password';
|
||||
|
||||
public string $type;
|
||||
public Model $model;
|
||||
public string $attribute;
|
||||
|
||||
public function __construct(Model $model, string $attribute){
|
||||
$this->type = self::TYPE_TEXT;
|
||||
$this->model = $model;
|
||||
$this->attribute = $attribute;
|
||||
}
|
||||
|
||||
public function __toString(){
|
||||
return sprintf('
|
||||
<div class="mb-3">
|
||||
<label>%s</label>
|
||||
<input type="%s" name="%s" value="%s" class="form-control%s">
|
||||
<div class="invalid-feedback">
|
||||
%s
|
||||
</div>
|
||||
</div>
|
||||
',
|
||||
$this->model->labels()[$this->attribute] ?? $this->attribute,
|
||||
$this->type,
|
||||
$this->attribute,
|
||||
$this->model->{$this->attribute},
|
||||
$this->model->hasError($this->attribute) ? ' is invalid' : '',
|
||||
$this->model->getFirstError($this->attribute)
|
||||
);
|
||||
}
|
||||
|
||||
public function passwordField(){
|
||||
$this->type = self::TYPE_PASSWORD;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
Regular → Executable
+30
-22
@@ -1,23 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
use app\core\Model;
|
||||
|
||||
class Form{
|
||||
public static function begin($action, $method){
|
||||
echo sprintf('<form action ="%s" method ="%s">', $action, $method);
|
||||
return new Form();
|
||||
}
|
||||
|
||||
public static function end(){
|
||||
echo '</form>';
|
||||
}
|
||||
|
||||
public function inputField(Model $model, $attribute){
|
||||
return new InputField($model, $attribute);
|
||||
}
|
||||
|
||||
public function button(){
|
||||
return new Button();
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
use app\core\Model;
|
||||
|
||||
class Form{
|
||||
private string $formDestinationPage = "";
|
||||
|
||||
public function __construct(string $formDestinationPage){
|
||||
$this->formDestinationPage = $formDestinationPage;
|
||||
}
|
||||
public function beginForm(): void
|
||||
{
|
||||
echo "<form action='$this->formDestinationPage' method ='POST'>";
|
||||
}
|
||||
|
||||
public function endForm(): void
|
||||
{
|
||||
echo "</form>";
|
||||
}
|
||||
|
||||
public function renderInputField(string $type, string $name, string $placeholder, string $value, ?string $error): void
|
||||
{
|
||||
echo new InputField($type, $name, $placeholder, $value, $error);
|
||||
}
|
||||
|
||||
public function renderButton(): void
|
||||
{
|
||||
echo new Button();
|
||||
}
|
||||
}
|
||||
Regular → Executable
+41
-35
@@ -1,36 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
|
||||
use app\core\Model;
|
||||
|
||||
class InputField extends BaseField
|
||||
{
|
||||
public const TYPE_TEXT = 'text';
|
||||
public const TYPE_PASSWORD = 'password';
|
||||
|
||||
public string $type;
|
||||
|
||||
public function __construct(Model $model, string $attribute)
|
||||
{
|
||||
$this->type = self::TYPE_TEXT;
|
||||
parent::__construct($model, $attribute);
|
||||
}
|
||||
|
||||
public function passwordField()
|
||||
{
|
||||
$this->type = self::TYPE_PASSWORD;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function renderInput(): string
|
||||
{
|
||||
return sprintf(
|
||||
'<input type="%s" name="%s" value="%s" class="form-control%s">',
|
||||
$this->type,
|
||||
$this->attribute,
|
||||
$this->model->{$this->attribute},
|
||||
$this->model->hasError($this->attribute) ? ' is invalid' : ''
|
||||
);
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
|
||||
class InputField
|
||||
{
|
||||
private string $type;
|
||||
private string $name;
|
||||
private string $placeholder;
|
||||
private string $value;
|
||||
private ?string $error;
|
||||
|
||||
public function __construct(string $type, string $name, string $placeholder, string $value, ?string $error)
|
||||
{
|
||||
$this->type = $this->getInputType($type);
|
||||
$this->name = $name;
|
||||
$this->placeholder = $placeholder;
|
||||
$this->value = $value;
|
||||
$this->error = $error;
|
||||
}
|
||||
public function __toString():string
|
||||
{
|
||||
$field = sprintf(
|
||||
'<input type="%s" name="%s" placeholder="%s" value="%s">',
|
||||
$this->type, $this->name, $this->placeholder, $this->value
|
||||
);
|
||||
|
||||
$errorField = NULL;
|
||||
if(!$this->error == NULL){
|
||||
$errorField = sprintf('<p class="errorStyle">%s</p>', $this->error);
|
||||
}
|
||||
|
||||
return $field.$errorField;
|
||||
}
|
||||
|
||||
private function getInputType(string $type): string{
|
||||
return match($type){
|
||||
"username", "email" => "text",
|
||||
"password" => "password"
|
||||
};
|
||||
}
|
||||
}
|
||||
Executable
+40
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
|
||||
use app\core\Model;
|
||||
|
||||
class Region extends BaseField
|
||||
{
|
||||
public const TYPE_TEXT = 'region';
|
||||
public string $type;
|
||||
|
||||
public function __construct(Model $model, string $attribute)
|
||||
{
|
||||
$this->type = self::TYPE_TEXT;
|
||||
parent::__construct($model, $attribute);
|
||||
}
|
||||
|
||||
public function startSelect(): string
|
||||
{
|
||||
return sprintf('<select class="%s" name="%s">',
|
||||
$this->type,
|
||||
$this->type,
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): ?string
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
public function endSelect(): string
|
||||
{
|
||||
return '</select>';
|
||||
}
|
||||
|
||||
public function renderInput(): string
|
||||
{
|
||||
return $this->startSelect().$this->content().$this->endSelect();
|
||||
}
|
||||
}
|
||||
Regular → Executable
+12
-12
@@ -1,13 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
|
||||
class TextareaField extends BaseField{
|
||||
public function renderInput(): string{
|
||||
return sprintf('<textarea name=%s class=form-control%s>%s</textarea>',
|
||||
$this->attribute,
|
||||
$this->model->hasError($this->attribute) ? ' is invalid' : '',
|
||||
$this->model->{$this->attribute}
|
||||
);
|
||||
}
|
||||
<?php
|
||||
|
||||
namespace app\core\form;
|
||||
|
||||
class TextareaField extends BaseField{
|
||||
public function renderInput(): string{
|
||||
return sprintf('<textarea name=%s class=form-control%s>%s</textarea>',
|
||||
$this->attribute,
|
||||
$this->model->hasError($this->attribute) ? ' is invalid' : '',
|
||||
$this->model->{$this->attribute}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\middlewares;
|
||||
use app\core\Application;
|
||||
use app\core\exceptions\ForbiddenException;
|
||||
|
||||
class AuthMiddleware extends BaseMiddleware{
|
||||
public array $actions = [];
|
||||
|
||||
public function __construct(array $actions = []){
|
||||
$this->actions = $actions;
|
||||
}
|
||||
|
||||
public function execute(){
|
||||
if(Application::isLoggedIn()){
|
||||
if(empty($this->actions) || in_array(Application::$app->controller->action, $this->actions)){
|
||||
throw new ForbiddenException;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace app\core\middlewares;
|
||||
|
||||
abstract class BaseMiddleware{
|
||||
abstract public function execute();
|
||||
}
|
||||
Reference in New Issue
Block a user