20240502#1

This commit is contained in:
User
2024-05-02 11:29:58 +03:00
parent 88b597d78d
commit e03c9bccfc
31 changed files with 208 additions and 147 deletions

View File

@@ -17,8 +17,8 @@ CONTAINER_DIR=application/config/container
CONTAINER_CACHE=var/cache/container CONTAINER_CACHE=var/cache/container
# Default page # Default page
PAGE404=templates/error/404.tpl PAGE404="/application/src/Presentation/templates/error/404.tpl"
PAGE501=templates/error/501.tpl PAGE501="/application/src/Presentation/templates/error/501.tpl"
# Users environment # Users environment
MYSQL_PARAM='{"host":"host.docker.internal", "user":"***user***", "pass":"***password***","base":"***basename***", "logsEnable":true}' MYSQL_PARAM='{"host":"host.docker.internal", "user":"***user***", "pass":"***password***","base":"***basename***", "logsEnable":true}'

View File

@@ -9,5 +9,5 @@ composer create-project rmphp/skeleton project-name
``` ```
```bash ```bash
composer create-project rmphp/skeleton:"^4.0" project-name composer create-project rmphp/skeleton:"^4.1" project-name
``` ```

View File

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

View File

@@ -1,2 +1,4 @@
<?php <?php
return (new \Rmphp\Content\Content('/templates/base.tpl'))->setSubtemplatePath('/templates'); return (new \Rmphp\Content\Content('/application/src/Presentation/templates/base.tpl'))->setSubtemplatePath('/application/src/Presentation/templates/')->setSubtemplatePathAlias([
"main" => "/src/Main/Presentation/templates",
]);

View File

@@ -1,13 +1,13 @@
# Index # Index
- key: "/" - key: "/"
routes: routes:
- action: "App\\Main\\Controllers\\IndexController" - action: "App\\Main\\Presentation\\Controllers\\IndexController"
method: "index" method: "index"
params: "" params: ""
# Empty # Empty
- key: "<@any>" - key: "<@any>"
routes: routes:
- action: "App\\Main\\Controllers\\IndexController" - action: "App\\Main\\Presentation\\Controllers\\IndexController"
method: "emptyAction" method: "emptyAction"
params: "" params: ""

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace Base\Services; namespace Base\Application;
use ReflectionClass; use ReflectionClass;

View File

@@ -1,11 +1,11 @@
<?php <?php
namespace Base\Services; namespace Base\Application;
use Throwable; use Throwable;
class ServiceException extends \Exception { class ApplicationException extends \Exception {
public array $data; public array $data;

View File

@@ -1,7 +1,7 @@
<?php <?php
namespace Base\Services; namespace Base\Application;
use Throwable; use Throwable;

View File

@@ -6,83 +6,12 @@
namespace Base\Domain; namespace Base\Domain;
use ReflectionClass; abstract class AbstractObject implements EntityInterface {
abstract class AbstractObject {
/** /**
* @param array $data * @return int|null
* @return static
* @throws DomainException
*/ */
public static function fromData(array $data) : static { public function getId(): mixed {
$self = new static(); return (isset($this->id)) ? (($this->id instanceof ValueObjectInterface) ? $this->id->get() : $this->id) : null;
$self->setProperties($data);
return $self;
}
/**
* @param array $data
* @return void
* @throws DomainException
*/
public function setProperties(array $data) : void {
$class = new ReflectionClass(static::class);
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()))) $this->{'set'.ucfirst($property->getName())}($value);
// Если тип свойства класс (valueObject)
elseif($property->hasType() && class_exists($property->getType()->getName())) $this->{$property->getName()} = new ($property->getType()->getName())($value);
// если значения не пустое
elseif(isset($value)) $this->{$property->getName()} = $value;
}
}
/**
* @param callable|null $method
* @return array
*/
public function getProperties(callable $method = null) : array {
$objectData = get_object_vars($this);
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,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,39 @@
<?php
namespace Base\Infrastructure\Repository;
use Base\Domain\EntityInterface;
use Rmphp\Storage\Mysql\MysqlStorageInterface;
abstract class AbstractMysqlRepository extends AbstractRepository {
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;
});
//dd($object, $in);
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\Infrastructure\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

@@ -1,6 +1,6 @@
<?php <?php
namespace Base\Repository; namespace Base\Infrastructure\Repository;
use Throwable; use Throwable;

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace Base\Controllers; namespace Base\Presentation\Controllers;
use Laminas\Diactoros\Response\HtmlResponse; use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\JsonResponse; use Laminas\Diactoros\Response\JsonResponse;

View File

@@ -1,10 +1,10 @@
<?php <?php
namespace Base\Controllers; namespace Base\Presentation\Controllers;
use Base\Application\ApplicationException;
use Base\Application\DTOException;
use Base\Domain\DomainException; use Base\Domain\DomainException;
use Base\Services\DTOException;
use Base\Services\ServiceException;
use Exception; use Exception;
use Throwable; use Throwable;
@@ -29,7 +29,7 @@ abstract class AbstractPageController extends AbstractController {
*/ */
public function checkError(Throwable $e) : string { public function checkError(Throwable $e) : string {
($e instanceof Exception) ? $this->logException($e) : $this->logError($e); ($e instanceof Exception) ? $this->logException($e) : $this->logError($e);
if($e instanceof DTOException || $e instanceof DomainException || $e instanceof ServiceException) return $e->getMessage(); if($e instanceof DTOException || $e instanceof DomainException || $e instanceof ApplicationException) return $e->getMessage();
return "Ошибка. Дата и время: ".date("d-m-Y H:i:s"); return "Ошибка. Дата и время: ".date("d-m-Y H:i:s");
} }
} }

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace Base\Controllers; namespace Base\Presentation\Controllers;
class NotFoundException extends \Exception { class NotFoundException extends \Exception {

View File

@@ -0,0 +1,12 @@
<header class="header">
<div class="header__logo">
<a class="header__logolink" href="/">&nbsp;</a>
</div>
<div class="header__freearea"></div>
<div class="header__user"><?=$this->user->fio ?? "Гость"?></div>
<div class="header__out">
<a href="/?logout">
<i class="header__outicon fa-solid fa-right-from-bracket"></i>
</a>
</div>
</header>

View File

@@ -1,35 +0,0 @@
<?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

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

View File

@@ -11,13 +11,14 @@
"laminas/laminas-diactoros": "^2.5", "laminas/laminas-diactoros": "^2.5",
"monolog/monolog": "^2.3", "monolog/monolog": "^2.3",
"php-di/php-di": "^6.3", "php-di/php-di": "^6.3",
"symfony/dotenv": "^6.2", "ramsey/uuid": "^4.7",
"rmphp/kernel": "^4.0", "rmphp/cache-file": "^1.0",
"rmphp/router": "^1.0", "rmphp/content": "^3.1",
"rmphp/content": "^3.0", "rmphp/kernel": "^4.1",
"rmphp/storage": "^3.0", "rmphp/router": "^1.2",
"rmphp/session": "^1.0", "rmphp/session": "^1.0",
"rmphp/cache-file": "^1.0" "rmphp/storage": "^3.1",
"symfony/dotenv": "^6.2"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {

View File

@@ -1,7 +1,7 @@
<?php <?php
namespace App\Main\Controllers; namespace App\Main\Presentation\Controllers;
use Base\Controllers\AbstractPageController; use Base\Presentation\Controllers\AbstractPageController;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
@@ -14,7 +14,7 @@ class IndexController extends AbstractPageController {
try { try {
//$this->addHeader("App-Mode", "Dev"); //$this->addHeader("App-Mode", "Dev");
$this->template()->setValue("title", "Главная"); $this->template()->setValue("title", "Главная");
$this->template()->setSubtemplate("main", "/main/index.tpl", [ $this->template()->setSubtemplate("main", "@main/index.tpl", [
"date" => (new \DateTime())->format('Y-m-d H:i:s') "date" => (new \DateTime())->format('Y-m-d H:i:s')
]); ]);
} }