20241102#1

This commit is contained in:
User
2024-11-02 07:31:03 +03:00
parent 1b0af12a46
commit 035f88ea72
33 changed files with 56 additions and 54 deletions

View File

@@ -0,0 +1,27 @@
<?php
namespace Base\Application;
use ReflectionClass;
abstract class AbstractDTO {
/**
* @param array $data
* @return static
*/
static function fromArray(array $data) : static {
$class = new ReflectionClass(static::class);
$self = new static();
foreach ($class->getProperties() as $property) {
$propertyNameSnakeCase = strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName()));
// data[propertyName] ?? data[property_name] ?? null
$value = $data[$property->getName()] ?? $data[$propertyNameSnakeCase] ?? null;
// если есть внутренний метод (приоритетная обработка)
if($class->hasMethod('set'.ucfirst($property->getName()))) $self->{'set'.ucfirst($property->getName())}($value);
// прямое присовение по умолчанию
elseif(isset($value)) $self->{$property->getName()} = $value;
}
return $self;
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Base\Application;
use Throwable;
class ApplicationException 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\Application;
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

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\Application\ApplicationException;
use Base\Application\DTOException;
use Base\Domain\DomainException;
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", "/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 {
($e instanceof Exception) ? $this->logException($e) : $this->logError($e);
if($e instanceof DTOException || $e instanceof DomainException || $e instanceof ApplicationException) return $e->getMessage();
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,17 @@
<?php
/**
* Created by PhpStorm.
* User: Zuev Yuri
*/
namespace Base\Domain;
abstract class AbstractObject implements EntityInterface {
/**
* @return int|null
*/
public function getId(): mixed {
return (isset($this->id)) ? (($this->id instanceof ValueObjectInterface) ? $this->id->get() : $this->id) : null;
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace Base\Domain;
use Throwable;
class DomainException 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,18 @@
<?php
/**
* Created by PhpStorm.
* User: Zuev Yuri
* Date: 23.04.2024
* Time: 3:58
*/
namespace Base\Domain;
interface EntityInterface {
/**
* @return int|null
*/
public function getId(): mixed;
}

View File

@@ -0,0 +1,16 @@
<?php
/**
* Created by PhpStorm.
* User: Zuev Yuri
* Date: 23.04.2024
* Time: 3:58
*/
namespace Base\Domain;
interface ValueObjectInterface {
public function get();
public function __toString(): string;
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Base\Repository;
use Base\Domain\EntityInterface;
use Rmphp\Storage\Mysql\MysqlStorageInterface;
abstract class AbstractMysqlRepository extends AbstractRepository {
public const DEBUG = false;
public function __construct(
public readonly MysqlStorageInterface $mysql
) {}
/**
* @param EntityInterface $object
* @param string $table
* @return mixed
* @throws RepositoryException
*/
public function saveEntity(EntityInterface $object, string $table) : mixed {
$in = $this->getProperties($object, function ($value){
return (is_string($value)) ? $this->mysql->escapeStr($value) : $value;
});
if(static::DEBUG) dd($object, $in, $table);
try {
if (!empty($object->getId()) && !empty($this->mysql->findById($table, $object->getId()))) {
$this->mysql->updateById($table, $in, $object->getId());
return $object->getId();
} else {
$this->mysql->insert($table, $in);
return (is_string($object->getId())) ? $object->getId() : $this->mysql->mysql()->insert_id;
}
} catch (\Throwable $throwable) {throw new RepositoryException($throwable->getMessage());}
}
}

View File

@@ -0,0 +1,12 @@
### Создание объекта из массива
```php
setProperties(array $data) : void
```
### Получение массива из объекта
```php
getProperties(callable $method = null) : array
```

View File

@@ -0,0 +1,93 @@
<?php
/**
* Created by PhpStorm.
* User: Zuev Yuri
* Date: 25.04.2024
* Time: 13:06
*/
namespace Base\Repository;
use Base\Domain\ValueObjectInterface;
use ReflectionClass;
use ReflectionException;
class AbstractRepository {
static array $classes = [];
/**
* @param string $class
* @param $data
* @return mixed
* @throws RepositoryException
*/
public function create(string $class, $data) : mixed {
try {
if(!isset(static::$classes[$class])) static::$classes[$class] = new ReflectionClass($class);
$object = new $class;
foreach (static::$classes[$class]->getProperties() as $property) {
$propertyNameSnakeCase = strtolower(preg_replace("'([A-Z])'", "_$1", $property->getName()));
// data[propertyName] ?? data[property_name] ?? null
$value = $data[$property->getName()] ?? $data[$propertyNameSnakeCase] ?? null;
// если есть внутренний метод (приоритетная обработка)
if(static::$classes[$class]->hasMethod('set'.ucfirst($property->getName()))) $object->{'set'.ucfirst($property->getName())}($value);
// Если тип свойства класс (valueObject)
elseif($property->hasType() && class_exists($property->getType()->getName())) $object->{$property->getName()} = new ($property->getType()->getName())($value);
// если значения не пустое
elseif(isset($value)) $object->{$property->getName()} = $value;
}
return $object;
}
catch (ReflectionException $exception) {
throw new RepositoryException($exception->getMessage());
}
}
/**
* @param object $class
* @param callable|null $method
* @return array
*/
public function getProperties(object $class, callable $method = null) : array {
$objectData = get_object_vars($class);
foreach ($objectData as $fieldName => $value)
{
// to option_id
$fieldNameSnakeCase = strtolower(preg_replace("'([A-Z])'", "_$1", $fieldName));
// если есть внутренний метод (приоритетная обработка)
if(method_exists($this, 'get'.ucfirst($fieldName))) {
$out[$fieldNameSnakeCase] = $this->{'get'.ucfirst($fieldName)}($value);
}
// если тип свойства класс (valueObject)
elseif($value instanceof ValueObjectInterface && null !== $value->get()) {
$out[$fieldNameSnakeCase] = $value->get();
}
// если передана callable функция через которую нужно пропустить все элементы
elseif(isset($method) && !is_array($value) && !is_object($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,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;
}
}