23 Commits
4.0.1 ... 4.5

Author SHA1 Message Date
User
8fc94aaeb8 20250224#1 2025-02-24 19:45:12 +03:00
User
aba089db5e 20250218#1 2025-02-18 02:39:16 +03:00
User
43e529dcad 20250128#2 2025-01-28 14:21:33 +03:00
User
5bef4f577e 20250128#1 2025-01-28 13:23:44 +03:00
User
b53c3f9815 20250127#1 2025-01-27 03:09:37 +03:00
User
11b1544317 20250113#4 2025-01-13 05:04:47 +03:00
User
9e4ae35455 20250113#3 2025-01-13 04:56:52 +03:00
User
23133c173c 20250113#2 2025-01-13 04:52:35 +03:00
User
bf529d83c8 20250113#1 2025-01-13 04:44:41 +03:00
User
794e82f7ce 20241102#2 2024-11-02 07:39:22 +03:00
User
035f88ea72 20241102#1 2024-11-02 07:31:03 +03:00
User
1b0af12a46 20241004#1 2024-10-04 03:00:11 +03:00
User
99f78f7362 20240814#2 2024-08-14 21:27:27 +03:00
User
72d2445bb2 20240814#1 2024-08-14 21:13:25 +03:00
User
40e771f1f2 20240719#1 2024-07-19 13:38:34 +03:00
User
858dfd17c0 20240708#2 2024-07-08 14:02:22 +03:00
User
c3e7bc6fc7 20240708#1 2024-07-08 13:57:42 +03:00
User
3ebbe07db6 20240508#1 2024-05-08 01:07:24 +03:00
User
e865eca689 20240505#3 2024-05-05 11:27:59 +03:00
User
e83753471c 20240505#2 2024-05-05 11:15:11 +03:00
User
6c571aa358 20240505#1 2024-05-05 11:09:18 +03:00
User
8b92eecba1 20240502#2 2024-05-02 12:01:28 +03:00
User
e03c9bccfc 20240502#1 2024-05-02 11:29:58 +03:00
44 changed files with 178 additions and 295 deletions

8
.editorconfig Normal file
View File

@@ -0,0 +1,8 @@
root = true
[*]
charset = utf-8
indent_style = tab
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

View File

@@ -10,15 +10,15 @@
# PROD / DEV # PROD / DEV
APP_MODE=DEV APP_MODE=DEV
APP_NODES_FILE=application/config/app.php
APP_COMPONENTS_FILE=application/config/app.php APP_COMPONENTS_FILE=application/config/components.php
APP_NODES_FILE=application/config/nodes.php CONTAINER_INI=application/config/container.php
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="/templates/error/404.tpl"
PAGE501=templates/error/501.tpl PAGE501="/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}'
REDIS_PARAM='{"host":"127.0.0.1","port":6379,"connectTimeout":2.5,"backoff":{"algorithm":1,"base":500,"cap":750}, "database":0, "defaultExpire":300}'

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.5" project-name
``` ```

View File

@@ -0,0 +1,41 @@
<?php
namespace Base\Application;
use Exception;
use ReflectionClass;
use Rmphp\Storage\Component\AbstractDataObject;
abstract class AbstractDTO extends AbstractDataObject {
/**
* @param array|object ...$data
* @return static
* @throws Exception
*/
public static function fromData(array|object ...$data) : static {
$array = array_map(function($item) {
return (is_object($item)) ? get_object_vars($item) : $item;
}, $data);
return self::fromArray(array_merge(...$array));
}
/**
* @param object $data
* @return static
* @throws Exception
*/
public static function fromObject(object $data) : static {
return self::fromArray(get_object_vars($data));
}
/**
* @param array $data
* @return static
* @throws Exception
*/
public static function fromArray(array $data) : static {
return self::fillObject(new ReflectionClass(static::class), new static(), $data);
}
}

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

@@ -2,9 +2,9 @@
namespace Base\Controllers; namespace Base\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;
@@ -18,7 +18,7 @@ abstract class AbstractPageController extends AbstractController {
public function exceptionPage(Exception $exception, array $data = []) : void { public function exceptionPage(Exception $exception, array $data = []) : void {
$this->logException($exception, $data); $this->logException($exception, $data);
$this->syslogger()->warning($exception->getMessage()." on ".$exception->getFile().":".$exception->getLine(), $data); $this->syslogger()->warning($exception->getMessage()." on ".$exception->getFile().":".$exception->getLine(), $data);
$this->template()->setSubtemplate("main", "/templates/error/errpage.tpl", [ $this->template()->setSubtemplate("main", "/error/errpage.tpl", [
"errorText" => "<span style='color:red'>Error: ".$exception->getMessage()." (".$exception->getCode().")"."</span>" "errorText" => "<span style='color:red'>Error: ".$exception->getMessage()." (".$exception->getCode().")"."</span>"
]); ]);
} }
@@ -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,21 +1,13 @@
<?php <?php
/**
* Правила для точек монтирования слоев
*/
# Example:
# ['key'=>'/', "action"=>"App\\Main\\Controllers\\IndexController", "method"=>"index"],
# ['key'=>'/', 'router'=>'application/config/routes/main/routes.php'],
# ['key'=>'/', 'router'=>[]],
return [ return [
/** ['key'=>'/', 'router'=>'application/config/routes/routes.php'],
* Путь к файлу фабрики возвращающий реализацию RouterInterface или сам экземпляр класса
*/
\Rmphp\Foundation\RouterInterface::class => 'application/config/factories/routerFactory.php',
/**
* Путь к файлу фабрики возвращающий реализацию TemplateInterface или сам экземпляр класса
*/
\Rmphp\Foundation\TemplateInterface::class => 'application/config/factories/templateFactory.php',
/**
* Путь к файлу фабрики возвращающий реализацию PSR-3 LoggerInterface или сам экземпляр класса
*/
\Psr\Log\LoggerInterface::class => 'application/config/factories/loggerFactory.php',
/**
* Путь к файлу фабрики возвращающий реализацию PSR-11 ContainerInterface или сам экземпляр класса
*/
\Psr\Container\ContainerInterface::class => 'application/config/factories/containerFactory.php',
]; ];

View File

@@ -0,0 +1,20 @@
<?php
return [
/**
* Путь к файлу фабрики возвращающий реализацию RouterInterface или сам экземпляр класса
*/
\Rmphp\Foundation\RouterInterface::class => 'application/config/components/routerFactory.php',
/**
* Путь к файлу фабрики возвращающий реализацию TemplateInterface или сам экземпляр класса
*/
\Rmphp\Foundation\TemplateInterface::class => 'application/config/components/templateFactory.php',
/**
* Путь к файлу фабрики возвращающий реализацию PSR-3 LoggerInterface или сам экземпляр класса
*/
\Psr\Log\LoggerInterface::class => 'application/config/components/loggerFactory.php',
/**
* Путь к файлу фабрики возвращающий реализацию PSR-11 ContainerInterface или сам экземпляр класса
*/
\Psr\Container\ContainerInterface::class => 'application/config/components/containerFactory.php',
];

View File

@@ -2,12 +2,13 @@
use DI\ContainerBuilder; use DI\ContainerBuilder;
$containerDir = (getenv("CONTAINER_DIR")) ?: "application/config/container"; $containerIni = (getenv("CONTAINER_INI")) ?: "application/config/container.php";
$containerCache = (getenv("CONTAINER_CACHE"))?:"var/cache/container"; $containerCache = (getenv("CONTAINER_CACHE")) ?: "var/cache/container";
$dependencies = require dirname(__DIR__,3).'/'.$containerIni;
$dependencies = glob(dirname(__DIR__,3)."/".$containerDir."/*.php");
$dependenciesCollection = array_map(function ($dependenciesFile){ $dependenciesCollection = array_map(function ($dependenciesFile){
return require $dependenciesFile; return require dirname(__DIR__,3)."/".$dependenciesFile;
}, $dependencies); }, $dependencies);
try { try {

View File

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

View File

@@ -0,0 +1,5 @@
<?php
return [
"application/config/container/services.php",
"application/config/container/settings.php",
];

View File

@@ -1,15 +1,10 @@
<?php <?php
use Rmphp\Cache\Cache;
use Rmphp\Cache\CacheInterface;
use Rmphp\Session\Session;
use Rmphp\Session\SessionInterface;
use Rmphp\Storage\Mysql\MysqlStorage; use Rmphp\Storage\Mysql\MysqlStorage;
use Rmphp\Storage\Mysql\MysqlStorageInterface; use Rmphp\Storage\Mysql\MysqlStorageInterface;
return [ 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(), 'App\Domain\Repository\*RepositoryInterface' => DI\autowire('App\Infrastructure\Repository\*Repository'),
CacheInterface::class => DI\create(Cache::class)->constructor("../var/cache"), 'App\*\Domain\Repository\*RepositoryInterface' => DI\autowire('App\*\Infrastructure\Repository\*Repository'),
'App\*\Domain\Repository\*Repository\*RepositoryInterface' => DI\autowire('App\*\Repository\Mysql\*Repository'),
]; ];

View File

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

View File

@@ -1,14 +0,0 @@
<?php
/**
* Правила для точек монтирования слоев
*/
# Example:
# ['key'=>'/', "action"=>"App\\Main\\Controllers\\IndexController", "method"=>"index"],
# ['key'=>'/', 'router'=>'config/routes/main/routes.php'],
# ['key'=>'/', 'router'=>[]],
return [
['key'=>'/', 'router'=>'application/config/routes/main/routes.php'],
];

View File

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

View File

@@ -1,9 +0,0 @@
<?php
$routes = glob(__DIR__."/{*.yaml}", GLOB_BRACE);
$routesCollection = array_map(function ($routesFile){
return file_get_contents($routesFile).PHP_EOL;
}, $routes);
return yaml_parse(implode($routesCollection));

View File

@@ -0,0 +1,16 @@
<?php
$cashFile = preg_replace("'.application.*$'",'', __DIR__).'/var/routes/'.md5(__FILE__);
if(getenv("APP_MODE") == "PROD" && file_exists($cashFile)){
return unserialize(file_get_contents($cashFile));
} else {
$routesCollection = array_map(function ($routesFile){
return file_get_contents($routesFile).PHP_EOL;
}, glob(__DIR__."/{*.yaml}", GLOB_BRACE));
$routes = yaml_parse(implode($routesCollection));
if (!is_dir(dirname($cashFile))) mkdir(dirname($cashFile), 0777, true);
file_put_contents($cashFile, serialize($routes));
return $routes;
}

View File

@@ -1,88 +0,0 @@
<?php
/**
* Created by PhpStorm.
* User: Zuev Yuri
*/
namespace Base\Domain;
use ReflectionClass;
abstract class AbstractObject {
/**
* @param array $data
* @return static
* @throws DomainException
*/
public static function fromData(array $data) : static {
$self = new static();
$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

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

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

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

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

View File

@@ -11,18 +11,19 @@
"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/content": "^3.1",
"rmphp/router": "^1.0", "rmphp/kernel": "^5.0",
"rmphp/content": "^3.0", "rmphp/router": "^1.2",
"rmphp/storage": "^3.0", "rmphp/session": "^1.1",
"rmphp/session": "^1.0", "rmphp/redis": "^1.0",
"rmphp/cache-file": "^1.0" "rmphp/storage": "^6.0",
"symfony/dotenv": "^6.2"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"App\\": "src", "App\\": "src",
"Base\\": "application/src" "Base\\": "application/base"
} }
}, },
"scripts": { "scripts": {

View File

@@ -11,12 +11,16 @@ require_once dirname(__DIR__).'/vendor/autoload.php';
(new Symfony\Component\Dotenv\Dotenv())->usePutenv()->loadEnv(dirname(__DIR__).'/.env'); (new Symfony\Component\Dotenv\Dotenv())->usePutenv()->loadEnv(dirname(__DIR__).'/.env');
error_reporting(0); ini_set('display_errors','Off'); if(getenv("APP_MODE") == 'DEBUG'){
error_reporting(E_ALL); ini_set('display_errors','On');
} else {
error_reporting(0); ini_set('display_errors','Off');
}
$request = ServerRequestFactory::fromGlobals(); $request = ServerRequestFactory::fromGlobals();
$app = new App(); $app = new App();
$response = $app->handler($request, (new Response())->withHeader("Content-Type", "text/html; charset=utf-8")); $response = $app->handler($request, new Response());
(new ResponseEmitter())->emit($response); (new ResponseEmitter())->emit($response);
if(($response->getStatusCode() !== 200 && getenv("APP_MODE") == 'DEV') || in_array("Dev", $response->getHeader("App-Mode"))){ if(($response->getStatusCode() !== 200 && getenv("APP_MODE") == 'DEV') || in_array("Dev", $response->getHeader("App-Mode"))){

View File

View File

@@ -1,10 +1,9 @@
<?php <?php
namespace App\Main\Controllers; namespace App\Infrastructure\Controllers;
use Base\Controllers\AbstractPageController; use Base\Controllers\AbstractPageController;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
class IndexController extends AbstractPageController { class IndexController extends AbstractPageController {
/** /**
@@ -14,11 +13,12 @@ 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", [
"date" => (new \DateTime())->format('Y-m-d H:i:s')
]);
} }
catch(\Throwable $e){$error = $this->checkError($e);} catch(\Throwable $e){$error = $this->checkError($e);}
return $this->render();
return $this->renderResponse("main", "@main/index.tpl", [
"date" => (new \DateTime())->format('Y-m-d H:i:s'),
"error" => $error ?? null
]);
} }
} }

View File

View File

@@ -0,0 +1,8 @@
<article>
<main>
<div class="main-block">
<div class="main-block__header">Hello</div>
<div class="main-block__text">Now is <?= $this->date ?></div>
</div>
</main>
</article>

0
templates/inc/footer.tpl Normal file
View File

12
templates/inc/header.tpl Normal file
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,8 +0,0 @@
<article>
<main>
<div class="main-block">
<div class="main-block__header">Hello</div>
<div class="main-block__text">Now is <?=$this->date?></div>
</div>
</main>
</article>