Skip to content

Commit

Permalink
Добавил Security
Browse files Browse the repository at this point in the history
Пофиксил косяк с array_pop в SupportedType->getName()
  • Loading branch information
NolikTop committed Aug 9, 2020
1 parent b7df14d commit 601f394
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 16 deletions.
31 changes: 27 additions & 4 deletions PrismaFrame.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
namespace GreenWix\prismaFrame;


use GreenWix\prismaFrame\security\Security;
use GreenWix\prismaFrame\type\SupportedType;
use Psr\Http\Message\ServerRequestInterface;
use ReflectionException;
use GreenWix\prismaFrame\controller\Checker;
use GreenWix\prismaFrame\controller\Controller;
Expand Down Expand Up @@ -32,6 +34,9 @@ private function __construct(){}
/** @var PrismaFrameSettings */
private static $settings;

/** @var Security */
private static $security;

/**
* @param PrismaFrameSettings $settings
* @throws InternalErrorException
Expand All @@ -46,7 +51,14 @@ public static function isDebug(): bool{
return self::$settings->debug;
}

/**
* @throws InternalErrorException
*/
public static function start(){
if(self::$security === null){
throw InternalError::NO_SECURITY();
}

self::$working = true;
}

Expand All @@ -55,18 +67,20 @@ public static function isWorking(): bool{
}

/**
* @param string $url
* @param string $httpMethod
* @param array $args
* @param ServerRequestInterface $req
* @return Response
* @throws InternalErrorException
*/
public static function handle(string $url, string $httpMethod, array $args): Response{
public static function handle(ServerRequestInterface $req): Response{
if(!self::$working){
throw InternalError::PRISMAFRAME_IS_NOT_STARTED("PrismaFrame::handle() не может быть выполнен, пока PrismaFrame не запущен (PrismaFrame::start())");
}

try {
$url = $req->getUri()->getPath();
$httpMethod = $req->getMethod();
$args = $req->getQueryParams();

if (!isset($args["v"])) {
throw RuntimeError::BAD_INPUT("Parameter \"v\" is required");
}
Expand All @@ -81,6 +95,8 @@ public static function handle(string $url, string $httpMethod, array $args): Res
$controller = $raw_2[0] ?? "";
$method = $raw_2[1] ?? "";

self::$security->beforeRequest($req);

return new Response(self::getController($controller)->callMethod($method, $httpMethod, $args), HTTPCodes::OK);
}catch(Throwable $e){
return Error::make($e);
Expand Down Expand Up @@ -120,6 +136,13 @@ public static function addController(Controller $controller){
self::$controllers[$controllerName] = $controller;
}

/**
* @param Security $security
*/
public static function setSecurity(Security $security){
self::$security = $security;
}

public static function addSupportedTypeClosure(string $name, \Closure $validator, bool $makeAlsoArrayType = false, string $readonOnBadValid = ''){
Checker::addSupportedTypeClosure($name, $validator, $makeAlsoArrayType, $readonOnBadValid);
}
Expand Down
5 changes: 1 addition & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,4 @@ prismaFrame - фреймворк для быстрого и удобного с
composer require greenwix/prismaframe:0.1
```

Вместо 0.1 можете использовать интересующую Вас версию из [списка](https://github.com/GreenWix/prismaFrame/releases)

## Руководство по использованию
[Wiki](https://github.com/GreenWix/prismaFrame/wiki)
Вместо 0.1 можете использовать интересующую Вас версию из [списка](https://github.com/GreenWix/prismaFrame/releases)
5 changes: 3 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@
}
],
"require": {
"ext-json": "*"
"ext-json": "*",
"laminas/laminas-diactoros": "^2.3"
},
"description": "Framework for creating API",
"autoload": {
"psr-4": {
"GreenWix\\prismaFrame\\": "/"
}
}
}
}
13 changes: 8 additions & 5 deletions controller/Checker.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use GreenWix\prismaFrame\error\internal\InternalErrorException;
use GreenWix\prismaFrame\error\runtime\RuntimeError;
use GreenWix\prismaFrame\error\runtime\RuntimeErrorException;
use Throwable;

final class Checker
{
Expand Down Expand Up @@ -86,11 +87,13 @@ public static function initSupportedTypes(){
}, true);

self::addSupportedTypeClosure('json', static function(string $var, &$readyData, array $extraData): bool{
// clear json_last_error()
json_encode(null);

$readyData = json_decode($var, true);
return json_last_error() === JSON_ERROR_NONE;
try {
$readyData = json_decode($var, true, JSON_THROW_ON_ERROR);
}catch(Throwable $e){
return false;
}
return true;
}, true);

self::addSupportedTypeClosure('float', static function(string $var, &$readyData, array $extraData): bool{
Expand Down Expand Up @@ -255,7 +258,7 @@ private static function parseDoc(string $data) : array {
$result = [];
foreach (explode("\n", $data) as $line){
$line = trim($line);
if($line{0} === '*' && $line{1} === ' ' && $line{2} === '@'){
if(isset($line{3}) && $line{0} === '*' && $line{1} === ' ' && $line{2} === '@'){
$raw = explode(' ', $line);
array_shift($raw); //Избавляемся от '*' в начале
$param = substr(array_shift($raw), 1);
Expand Down
4 changes: 4 additions & 0 deletions error/internal/InternalError.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ public static function PRISMAFRAME_ALREADY_STARTED(string $message): InternalErr
return new InternalErrorException(InternalErrorCodes::PRISMAFRAME_ALREADY_STARTED, $message);
}

public static function NO_SECURITY(): InternalErrorException{
return new InternalErrorException(InternalErrorCodes::NO_SECURITY, "Не установлен Security менеджер. Установите его при помощи метода PrismaFrame::setSecurity()");
}

public static function WRONG_ARGS_ORDER(string $controller, string $method): InternalErrorException{
return new InternalErrorException(InternalErrorCodes::WRONG_ARGS_ORDER, "Порядок аргументов в php-doc метода \"{$controller}.{$method}\" не совпадает с порядком аргументов функции");
}
Expand Down
1 change: 1 addition & 0 deletions error/internal/InternalErrorCodes.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ interface InternalErrorCodes
const WRONG_HTTP_METHOD = 0x09; // Метод хочет принимать HTTP методы, которые не поддерживаются PrismaFrame
const UNKNOWN_PARAMETER_TYPE = 0x0a;
const WRONG_ARGS_ORDER = 0x0b; // Порядок аргументов в php-doc не совпадает с порядком аргументов функции
const NO_SECURITY = 0x0c; // Не установлен Security менеджер

}
24 changes: 24 additions & 0 deletions security/Security.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php


namespace GreenWix\prismaFrame\security;


use Psr\Http\Message\ServerRequestInterface;

abstract class Security
{

/**
* @param ServerRequestInterface $request
* @return mixed
*/
abstract public function beforeRequest(ServerRequestInterface $request): void;

/**
* @param ServerRequestInterface $request
* @param string $message
*/
abstract public function report(ServerRequestInterface $request, string $message): void;

}
3 changes: 2 additions & 1 deletion type/SupportedType.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ public function __construct(string $input = "", array $extraData = []){
}

public function getName(): string{
return array_pop(explode("\\", get_class($this)));
$array = explode("\\", get_class($this));
return array_pop($array);
}

abstract public function isArrayType(): bool;
Expand Down

0 comments on commit 601f394

Please sign in to comment.