20240412#1

This commit is contained in:
User
2024-04-12 03:18:04 +03:00
parent 035783e264
commit c2d2ad9177
20 changed files with 292 additions and 50 deletions

View File

@@ -14,8 +14,8 @@
"symfony/dotenv": "^6.2",
"rmphp/kernel": "^3.0",
"rmphp/router": "^1.0",
"rmphp/content": "^2.0",
"rmphp/storage": "^2.0",
"rmphp/content": "^3.0",
"rmphp/storage": "^3.0",
"rmphp/session": "^1.0",
"rmphp/cache-file": "^1.0"
},

View File

@@ -11,5 +11,5 @@ return [
MysqlStorageInterface::class => DI\create(MysqlStorage::class)->constructor(json_decode(getenv("MYSQL_PARAM"), true)),
SessionInterface::class => DI\create(Session::class)->constructor(),
CacheInterface::class => DI\create(Cache::class)->constructor("../var/cache"),
'App\*\Domain\Repository\*RepositoryInterface' => DI\autowire('App\*\Repository\Mysql\*Repository'),
'App\*\Domain\Repository\*Repository\*RepositoryInterface' => DI\autowire('App\*\Repository\Mysql\*Repository'),
];

View File

@@ -1,2 +1,2 @@
<?php
return (new \Rmphp\Content\Content('templates/base.tpl'))->setSubtemplePath('templates');
return (new \Rmphp\Content\Content('/templates/base.tpl'))->setSubtemplatePath('/templates');

View File

@@ -2,15 +2,14 @@
/**
* Правила для точек монтирования модулей
* Каждый массив определяет порядок срабатывания, часть url с которого
*/
# Example:
# ['key'=>'/', "action"=>"App\\Main\\Controllers\\IndexController", "method"=>"index"],
# ['key'=>'/', 'router'=>'config/routes/main/routes.php'],
# ['key'=>'/', 'router'=>'config/routes/main.yaml'],
# ['key'=>'/', 'router'=>[]],
return [
['key'=>'/', 'router'=>'config/routes/main.yaml'],
['key'=>'/', 'router'=>'config/routes/main/routes.php'],
];

View File

@@ -1,12 +0,0 @@
- key: "/"
routes:
- action: "App\\Main\\Controllers\\IndexController"
method: "index"
params: ""
# Empty
- key: "[any]"
routes:
- action: "App\\Main\\Controllers\\IndexController"
method: "emptyAction"
params: ""

View File

@@ -6,7 +6,7 @@
params: ""
# Empty
- key: "[any]"
- key: "<@any>"
routes:
- action: "App\\Main\\Controllers\\IndexController"
method: "emptyAction"

View File

@@ -12,7 +12,7 @@ require_once dirname(__DIR__).'/vendor/autoload.php';
(new Symfony\Component\Dotenv\Dotenv())->usePutenv()->loadEnv(dirname(__DIR__).'/.env');
error_reporting(0); ini_set('display_errors','Off');
if(getenv("APP_MODE") == 'DEV'){
if(getenv("APP_MODE") == 'ERR'){
error_reporting(E_ALL); ini_set('display_errors','On');
}
@@ -23,7 +23,7 @@ $response = $app->handler($request, (new Response())->withHeader("Content-Type",
(new ResponseEmitter())->emit($response);
if(getenv("APP_MODE") == 'DEV' && in_array("Dev", $response->getHeader("App-Mode"))){
if(in_array("Dev", $response->getHeader("App-Mode"))){
$app->syslogger()->dump("Response", $response);
addShutdownInfo($app->syslogger()->getLogs());
}

View File

@@ -7,7 +7,6 @@ use Laminas\Diactoros\Response\JsonResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Diactoros\Response\TextResponse;
use Psr\Http\Message\ResponseInterface;
use Rmphp\Foundation\Exceptions\AppException;
use Rmphp\Kernel\Main;
use Throwable;
@@ -81,11 +80,24 @@ abstract class AbstractController extends Main {
}
/**
* @param string $point
* @param string $subtemplate
* @param array $data
* @param int $status
* @param array $headers
* @return ResponseInterface
*/
public function renderResponse(int $status = 200, array $headers = []) : ResponseInterface {
public function renderResponse(string $point, string $subtemplate, array $data = [], int $status = 200, array $headers = []) : ResponseInterface {
$this->template()->setSubtemplate($point, $this->getTemplatePath($subtemplate), $data);
return new HtmlResponse($this->template()->getResponse(), $status, array_merge($this->globals()->response()->getHeaders(), $headers));
}
/**
* @param int $status
* @param array $headers
* @return ResponseInterface
*/
public function render(int $status = 200, array $headers = []) : ResponseInterface {
return new HtmlResponse($this->template()->getResponse(), $status, array_merge($this->globals()->response()->getHeaders(), $headers));
}
@@ -94,7 +106,7 @@ abstract class AbstractController extends Main {
* @param string $string
* @return void
*/
public function setTemplateValue(string $point, string $string) : void {
public function templSetValue(string $point, string $string) : void {
$this->template()->setValue($point, $string);
}
@@ -103,41 +115,35 @@ abstract class AbstractController extends Main {
* @param string $string
* @return void
*/
public function addTemplateValue(string $point, string $string) : void {
public function templAddValue(string $point, string $string) : void {
$this->template()->addValue($point, $string);
}
/**
* @param string $point
* @param string $subTempl
* @param string $subtemplate
* @param array $resource
* @return void
*/
public function setSubtemplate(string $point, string $subTempl, array $resource = []) : void {
$this->template()->setSubtemple($point, $subTempl, $resource);
}
/**
* @param string $point
* @param string $subTempl
* @param array $resource
* @return void
*/
public function addSubtemplate(string $point, string $subTempl, array $resource = []) : void {
$this->template()->addSubtemple($point, $subTempl, $resource);
public function templSetSubtemplate(string $point, string $subtemplate, array $resource = []) : void {
$this->template()->setSubtemplate($point, $this->getTemplatePath($subtemplate), $resource);
}
/**
* @param string $point
* @param string $subtemplate
* @param array $data
* @param int $status
* @param array $headers
* @return ResponseInterface
* @param array $resource
* @return void
*/
public function render(string $point, string $subtemplate, array $data = [], int $status = 200, array $headers = []) : ResponseInterface {
$this->template()->setSubtemple($point, $subtemplate, $data);
return new HtmlResponse($this->template()->getResponse(), $status, array_merge($this->globals()->response()->getHeaders(), $headers));
public function templAddSubtemplate(string $point, string $subtemplate, array $resource = []) : void {
$this->template()->addSubtemplate($point, $this->getTemplatePath($subtemplate), $resource);
}
/**
* @param string $path
* @return string
*/
public function getTemplatePath(string $path) : string {
return $path;
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Common\Controllers;
use App\Common\Repository\RepositoryException;
use App\Common\Services\DTOException;
use App\Common\Services\ServiceException;
use Exception;
use Throwable;
abstract class AbstractPageController extends AbstractController {
/**
* @param Exception $exception
* @param array $data
* @return void
*/
public function exceptionPage(Exception $exception, array $data = []) : void {
$this->logException($exception, $data);
$this->syslogger()->warning($exception->getMessage()." on ".$exception->getFile().":".$exception->getLine(), $data);
$this->template()->setSubtemplate("main", "/templates/error/errpage.tpl", [
"errorText" => "<span style='color:red'>Error: ".$exception->getMessage()." (".$exception->getCode().")"."</span>"
]);
}
/**
* @param Throwable $e
* @return string
*/
public function checkError(Throwable $e) : string {
if($e instanceof DTOException || $e instanceof ServiceException || $e instanceof RepositoryException) return $e->getMessage();
($e instanceof Exception) ? $this->logException($e) : $this->logError($e);
return "Ошибка. Дата и время: ".date("d-m-Y H:i:s");
}
}

View File

@@ -0,0 +1,82 @@
<?php
/**
* Created by PhpStorm.
* User: Zuev Yuri
*/
namespace App\Common\Domain;
abstract class AbstractObject {
/**
* @param array $data
* @return static
*/
public static function fromData(array $data) : static {
$self = new static();
$self->setProperties($data);
return $self;
}
/**
* @param array $data
* @return $this
*/
public function setProperties(array $data) : self {
$propArray = array_keys(get_class_vars(get_class($this)));
foreach ($propArray as $propName)
{
$propNameSnakeCase = strtolower(preg_replace("'([A-Z])'", "_$1", $propName));
// если в переданном массиве ключ и свойство совпадают optionId = optionId
if(isset($data[$propName])) {
$this->{$propName} = (method_exists($this, 'set'.ucfirst($propName))) ? $this->{'set'.ucfirst($propName)}($data[$propName]) : $data[$propName];
}
// если свойство в снэйккесе совподает с ключем в массиве option_id = optionId
elseif(isset($data[$propNameSnakeCase])) {
$this->{$propName} = (method_exists($this, 'set'.ucfirst($propName))) ? $this->{'set'.ucfirst($propName)}($data[$propNameSnakeCase]) : $data[$propNameSnakeCase];
}
}
return $this;
}
/**
* @param callable|null $method
* @return array
*/
public function getProperties(callable $method = null) : array {
$objectData = get_object_vars($this);
foreach ($objectData as $fieldName => $value)
{
$fieldNameSnakeCase = strtolower(preg_replace("'([A-Z])'", "_$1", $fieldName));
// если есть внутренний метод
if(method_exists($this, 'get'.ucfirst($fieldName))) {
$out[$fieldNameSnakeCase] = $this->{'get'.ucfirst($fieldName)}($value);
}
// если есть callable функция
elseif(isset($method) && !is_array($value)) {
$out[$fieldNameSnakeCase] = $method($value);
}
// если это логическое значение
elseif(is_bool($value)){
$out[$fieldNameSnakeCase] = (int) $value;
}
// если это дробное число
elseif(is_float($value)) {
$out[$fieldNameSnakeCase] = $value;
}
// если это целое число
elseif(is_int($value)) {
$out[$fieldNameSnakeCase] = $value;
}
// если это строка
elseif(is_string($value)) {
$out[$fieldNameSnakeCase] = $value;
}
}
return $out ?? [];
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace App\Common\Repository;
use App\Common\Domain\AbstractObject;
use Rmphp\Storage\Mysql\MysqlStorageInterface;
abstract class AbstractMysqlRepository {
public function __construct(
public readonly MysqlStorageInterface $mysql
) {}
/**
* @throws RepositoryException
*/
public function saveEntity(AbstractObject $object, string $table) : AbstractObject {
$in = $object->getProperties(function ($value){
return (is_string($value)) ? $this->mysql->escapeStr($value) : $value;
});
try {
if (!empty($object->id) && !empty($this->mysql->findById($table, $object->id))) {
$this->mysql->updateById($table, $in, $object->id);
} else {
$this->mysql->insert($table, $in);
$object->id = $this->mysql->mysql()->insert_id;
}
} catch (\Throwable $throwable) {throw new RepositoryException($throwable->getMessage());}
return $object;
}
}

View File

@@ -0,0 +1,81 @@
<?php
namespace App\Common\Services;
use Exception;
abstract class AbstractDTO {
/**
* @param array $data
* @return static
* @throws Exception
*/
static function fromArray(array $data) : static {
$self = new static();
$propArray = array_keys(get_class_vars(get_class($self)));
foreach($propArray as $propName){
$propNameSnakeCase = strtolower(preg_replace("'([A-Z])'", "_$1", $propName));
if(method_exists($self, "requireAssert".ucfirst($propName))){
if(isset($data[$propName])) {
$self->{"requireAssert".ucfirst($propName)}($data[$propName]);
}
elseif(isset($data[$propNameSnakeCase])) {
$self->{"requireAssert".ucfirst($propName)}($data[$propNameSnakeCase]);
}
else{
throw new DTOException("Отсутствует обязательное значение");
}
}
}
foreach($data as $key => $item){
try {
$camelCaseKey = str_replace('_', '', ucwords($key, "_"));
if(method_exists($self, "assert".$camelCaseKey)) {
$self->{'assert'.$camelCaseKey}($item);
} elseif(in_array(lcfirst($camelCaseKey), $propArray)) {
$self->{lcfirst($camelCaseKey)} = $item;
}
}
catch (\Error $error) {
$errorKey[$key] = $error->getMessage();
}
if(!empty($errorKey)) throw new Exception(json_encode(["data"=>$data, "error"=>$errorKey]));
}
return $self;
}
/**
* @param $value
* @return bool
*/
public function validateInt($value) : bool {
return (is_numeric($value));
}
/**
* @param $value
* @return bool
*/
public function validateFloat($value) : bool {
return (is_float((float) $value));
}
/**
* @param $value
* @return bool
*/
public function validateBoolean($value) : bool {
return (is_bool($value));
}
/**
* @param $value
* @return bool
*/
public function validateEmail($value) : bool {
return (filter_var($value, FILTER_VALIDATE_EMAIL));
}
}

View File

@@ -4,7 +4,7 @@ namespace App\Common\Services;
use Rmphp\Kernel\Main;
class AbstractService extends Main {
abstract class AbstractService extends Main {
}

View File

@@ -0,0 +1,16 @@
<?php
namespace App\Common\Services;
use Throwable;
class DTOException extends \Exception {
public array $data;
public function __construct($message="", $code=0, array $data = [], Throwable $previous=null) {
parent::__construct($message, $code, $previous);
$this->data = $data;
}
}

View File

@@ -13,12 +13,12 @@ class IndexController extends AbstractController {
*/
public function index() : bool|ResponseInterface {
try {
$this->addHeader("App-Mode", "Dev");
//$this->addHeader("App-Mode", "Dev");
$this->template()->setValue("title", "Главная");
$this->template()->setSubtemple("main", "main/index.tpl", [
$this->template()->setSubtemplate("main", "/main/index.tpl", [
"date" => (new \DateTime())->format('Y-m-d H:i:s')
]);
return $this->renderResponse();
return $this->render();
}
catch(ServiceException $exception){}
return true;