20240413#7

This commit is contained in:
User
2024-04-13 11:33:47 +03:00
parent 041ee17263
commit cb5408be4a
24 changed files with 16 additions and 15 deletions

View File

View File

@@ -0,0 +1,149 @@
<?php
namespace Base\Controllers;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\JsonResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\Diactoros\Response\TextResponse;
use Psr\Http\Message\ResponseInterface;
use Rmphp\Kernel\Main;
use Throwable;
abstract class AbstractController extends Main {
/**
* @param Throwable $throwable
* @param array $data
* @return void
*/
public function logException(Throwable $throwable, array $data = []) : void {
$this->logger()->warning($throwable->getMessage()." on ".$throwable->getFile().":".$throwable->getLine(), $data);
}
/**
* @param Throwable $throwable
* @param array $data
* @return void
*/
public function logError(Throwable $throwable, array $data = []) : void {
$this->logger()->error($throwable->getMessage()." on ".$throwable->getFile().":".$throwable->getLine(), $data);
}
/**
* @param string $name
* @param string $value
* @return void
*/
public function addHeader(string $name, string $value) : void {
$this->globals()->addHeader($name, $value);
}
/**
* @param $html
* @param int $status
* @param array $headers
* @return ResponseInterface
*/
public function htmlResponse($html, int $status = 200, array $headers = []) : ResponseInterface {
return new HtmlResponse($html, $status, array_merge($this->globals()->response()->getHeaders(), $headers));
}
/**
* @param $text
* @param int $status
* @param array $headers
* @return ResponseInterface
*/
public function textResponse($text, int $status = 200, array $headers = []) : ResponseInterface {
return new TextResponse($text, $status, array_merge($this->globals()->response()->getHeaders(), $headers));
}
/**
* @param array $array
* @param int $status
* @param array $headers
* @return ResponseInterface
*/
public function jsonResponse(array $array, int $status = 200, array $headers = []) : ResponseInterface {
return new JsonResponse($array, $status, array_merge($this->globals()->response()->getHeaders(), $headers), JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
}
/**
* @param string $url
* @param int $status
* @param array $headers
* @return ResponseInterface
*/
public function redirectResponse(string $url, int $status = 302, array $headers = []) : ResponseInterface {
return new RedirectResponse($url, $status, array_merge($this->globals()->response()->getHeaders(), $headers));
}
/**
* @param string $point
* @param string $subtemplate
* @param array $data
* @param int $status
* @param array $headers
* @return 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));
}
/**
* @param string $point
* @param string $string
* @return void
*/
public function templSetValue(string $point, string $string) : void {
$this->template()->setValue($point, $string);
}
/**
* @param string $point
* @param string $string
* @return void
*/
public function templAddValue(string $point, string $string) : void {
$this->template()->addValue($point, $string);
}
/**
* @param string $point
* @param string $subtemplate
* @param array $resource
* @return void
*/
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 $resource
* @return void
*/
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 Base\Controllers;
use Base\Repository\RepositoryException;
use Base\Services\DTOException;
use Base\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,7 @@
<?php
namespace Base\Controllers;
class NotFoundException extends \Exception {
}

View File

@@ -0,0 +1,82 @@
<?php
/**
* Created by PhpStorm.
* User: Zuev Yuri
*/
namespace Base\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 Base\Repository;
use Base\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,15 @@
<?php
namespace Base\Repository;
use Throwable;
class RepositoryException 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

@@ -0,0 +1,81 @@
<?php
namespace Base\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

@@ -0,0 +1,10 @@
<?php
namespace Base\Services;
use Rmphp\Kernel\Main;
abstract class AbstractService extends Main {
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Base\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

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