Compare commits
19 Commits
Author | SHA1 | Date | |
---|---|---|---|
6a4ea3f351 | |||
f95e4082ef | |||
9011ccf557 | |||
e1a6483556 | |||
95ddffba30 | |||
41bf8ab56a | |||
3d31c92628 | |||
1f5685a20d | |||
22ad7304f9 | |||
![]() |
7777d7af17 | ||
![]() |
483814b6a5 | ||
![]() |
e7a6b9cebe | ||
![]() |
a4949ebc52 | ||
![]() |
aeed2d21cc | ||
![]() |
81990de191 | ||
![]() |
b6f90b7001 | ||
![]() |
db36a0a27e | ||
![]() |
ebfa14d8d6 | ||
![]() |
2d06e386f5 |
0
.gitignore
vendored
Normal file → Executable file
0
.gitignore
vendored
Normal file → Executable file
11
LICENSE
Normal file
11
LICENSE
Normal file
@@ -0,0 +1,11 @@
|
||||
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
|
||||
Version 2, December 2004
|
||||
|
||||
Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim or modified copies of this license document, and changing it is allowed as long as the name is changed.
|
||||
|
||||
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. You just DO WHAT THE FUCK YOU WANT TO.
|
64
README.md
Normal file
64
README.md
Normal file
@@ -0,0 +1,64 @@
|
||||
The MINIMAL framework that does **not limit your project with its own rules**, has **no dependencies**, implements the **best practices** of popular MVC-frameworks, it **VERY fast** and **optimized** for all the innovations in **PHP 8.2** 🤟
|
||||
|
||||
Can be configured to work with **any database** `core::$session` and **any HTML template engine** `$this->view`
|
||||
*personally, i prefer **ArangoDB** and **Twig***
|
||||
|
||||
## Nearest plans (first half of 2025)
|
||||
1. Add **middlewares** technology
|
||||
2. Route sorting in the router `router::sort()`
|
||||
3. Add trigger routes from within routes
|
||||
4. Think about adding asynchronous executions
|
||||
5. Write an article describing the principles of the framework
|
||||
|
||||
## Installation
|
||||
Execute: `composer require mirzaev/minimal`
|
||||
|
||||
## Usage
|
||||
*index.php*
|
||||
```php
|
||||
// Initializing the router
|
||||
$router = new router;
|
||||
|
||||
// Initializing of routes
|
||||
$router
|
||||
->write('/', 'catalog', 'index', 'GET')
|
||||
->write('/search', 'catalog', 'search', 'POST')
|
||||
->write('/session/connect/telegram', 'session', 'telegram', 'POST')
|
||||
->write('/product/$id', 'catalog', 'product', 'POST')
|
||||
->write('/$categories...', 'catalog', 'index', 'POST'); // Collector (since 0.3.0)
|
||||
|
||||
// Initializing the core
|
||||
$core = new core(namespace: __NAMESPACE__, router: $router, controller: new controller(false), model: new model(false));
|
||||
|
||||
// Handle the request
|
||||
echo $core->start();
|
||||
```
|
||||
|
||||
## Examples of projects based on MINIMAL
|
||||
|
||||
### ebala
|
||||
**Repository:** https://git.mirzaev.sexy/mirzaev/ebala<br>
|
||||
**Github mirror:** https://github.com/mature-woman/ebala<br>
|
||||
*I earned more than a **million rubles** from this project*<br>
|
||||
*Repositories **may** be closed at the request of the customer*<br>
|
||||
|
||||
### huesos
|
||||
**Repository:** https://git.mirzaev.sexy/mirzaev/huesos<br>
|
||||
**Guthub mirror:** https://github.com/mature-woman/huesos<br>
|
||||
*The basis for developing chat-robots with Web App technology (for example for Telegram)*<br>
|
||||
|
||||
### arming_bot
|
||||
**Repository:** https://git.mirzaev.sexy/mirzaev/arming_bot<br>
|
||||
**Guthub mirror:** https://github.com/mature-woman/arming_bot<br>
|
||||
*Chat-robot based on huesos*<br>
|
||||
|
||||
### notchat
|
||||
**Repository:** https://git.mirzaev.sexy/mirzaev/notchat<br>
|
||||
**Github mirror:** https://github.com/mature-woman/notchat<br>
|
||||
*P2P chat project with different blockchains and smart stuff*<br>
|
||||
|
||||
### site-repression
|
||||
**Link:** https://repression.mirzaev.sexy<br>
|
||||
**Repository:** https://git.mirzaev.sexy/mirzaev/site-repression<br>
|
||||
**Github mirror:** https://github.com/mature-woman/site-repression<br>
|
||||
*A simple site for my article about **political repressions in Russia** and my **kidnapping by Wagner PMC operatives** from my house*<br>
|
76
composer.json
Normal file → Executable file
76
composer.json
Normal file → Executable file
@@ -1,44 +1,32 @@
|
||||
{
|
||||
"name": "mirzaev/minimal",
|
||||
"type": "framework",
|
||||
"description": "Легковесный MVC фреймворк который следует твоим правилам, а не диктует свои",
|
||||
"keywords": [
|
||||
"mvc",
|
||||
"framework"
|
||||
],
|
||||
"homepage": "https://git.hood.su/mirzaev/minimal",
|
||||
"license": "WTFPL",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Arsen Mirzaev Tatyano-Muradovich",
|
||||
"email": "arsen@mirzaev.sexy",
|
||||
"homepage": "https://mirzaev.sexy",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"support": {
|
||||
"docs": "https://git.hood.su/mirzaev/minimal/manual",
|
||||
"issues": "https://git.hood.su/mirzaev/minimal/issues"
|
||||
},
|
||||
"require": {
|
||||
"php": "~8.0",
|
||||
"psr/log": "~3.0",
|
||||
"twig/twig": "^3.3"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "~9.5"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-PDO": "Для работы с базами данных на SQL (MySQL, PostreSQL...)"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"mirzaev\\minimal\\": "mirzaev/minimal/system"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
"psr-4": {
|
||||
"mirzaev\\minimal\\tests\\": "mirzaev/minimal/tests"
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
"name": "mirzaev/minimal",
|
||||
"type": "framework",
|
||||
"description": "My vision of a good framework",
|
||||
"keywords": [
|
||||
"mvc",
|
||||
"framework",
|
||||
"lightweight"
|
||||
],
|
||||
"license": "WTFPL",
|
||||
"homepage": "https://git.mirzaev.sexy/mirzaev/minimal",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Arsen Mirzaev Tatyano-Muradovich",
|
||||
"email": "arsen@mirzaev.sexy",
|
||||
"homepage": "https://mirzaev.sexy",
|
||||
"role": "Programmer"
|
||||
}
|
||||
],
|
||||
"support": {
|
||||
"docs": "https://git.mirzaev.sexy/mirzaev/minimal/wiki",
|
||||
"issues": "https://git.mirzaev.sexy/mirzaev/minimal/issues"
|
||||
},
|
||||
"require": {
|
||||
"php": "~8.4"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"mirzaev\\minimal\\": "mirzaev/minimal/system"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
4640
composer.lock
generated
Normal file → Executable file
4640
composer.lock
generated
Normal file → Executable file
File diff suppressed because it is too large
Load Diff
86
mirzaev/minimal/system/controller.php
Executable file
86
mirzaev/minimal/system/controller.php
Executable file
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal;
|
||||
|
||||
// Files of the project
|
||||
use mirzaev\minimal\model,
|
||||
mirzaev\minimal\core,
|
||||
mirzaev\minimal\traits\magic;
|
||||
|
||||
// Build-in libraries
|
||||
use exception;
|
||||
|
||||
/**
|
||||
* Controller
|
||||
*
|
||||
* @var core $core An instance of the core
|
||||
* @var model $model An instance of the model connected in the core
|
||||
* @var view $view View template engine instance (twig)
|
||||
* @var core $core An instance of the core
|
||||
* @var core $core An instance of the core
|
||||
*
|
||||
* @method self __construct(core $core) Constructor
|
||||
*
|
||||
* @package mirzaev\minimal
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
class controller
|
||||
{
|
||||
use magic;
|
||||
|
||||
/**
|
||||
* Core
|
||||
*
|
||||
* @var core $core An instance of the core
|
||||
*/
|
||||
public core $core {
|
||||
// Read
|
||||
get => $this->core;
|
||||
}
|
||||
|
||||
/**
|
||||
* Model
|
||||
*
|
||||
* @var model $model An instance of the model connected in the core
|
||||
*/
|
||||
public model $model {
|
||||
// Write
|
||||
set (model $model) {
|
||||
$this->model ??= $model;
|
||||
}
|
||||
|
||||
// Read
|
||||
get => $this->model;
|
||||
}
|
||||
|
||||
/**
|
||||
* View
|
||||
*
|
||||
* @var view $view View template engine instance (twig)
|
||||
*/
|
||||
public object $view {
|
||||
// Write
|
||||
set (object $view) {
|
||||
$this->view ??= $view;
|
||||
}
|
||||
|
||||
// Read
|
||||
get => $this->view;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param core $core The instance of the core
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function __construct(core $core) {
|
||||
// Writing the core into the property
|
||||
$this->core = $core;
|
||||
}
|
||||
}
|
@@ -1,148 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal\controllers;
|
||||
|
||||
use mirzaev\minimal\core;
|
||||
use mirzaev\minimal\models\model;
|
||||
|
||||
use Twig\Loader\FilesystemLoader;
|
||||
use Twig\Environment as view;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Контроллер
|
||||
*
|
||||
* @package mirzaev\minimal\controllers
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
class controller
|
||||
{
|
||||
/**
|
||||
* @var model $model Модель
|
||||
*/
|
||||
protected model $model;
|
||||
|
||||
/**
|
||||
* @var view $view Шаблонизатор представления
|
||||
*/
|
||||
protected view $view;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __construct()
|
||||
{
|
||||
// Установка значения по умолчанию для модели (если будет найдена)
|
||||
$this->__get('model');
|
||||
// Установка значения по умолчанию для шаблонизатора представлений
|
||||
$this->__get('view');
|
||||
}
|
||||
|
||||
/**
|
||||
* Отрисовка шаблона
|
||||
*
|
||||
* @param string $route Маршрут
|
||||
*/
|
||||
public function view(string $route)
|
||||
{
|
||||
// Чтение представления по шаблону пути: "/views/[controller]/index
|
||||
// Никаких слоёв и шаблонизаторов
|
||||
// Не стал в ядре записывать путь до шаблонов
|
||||
if (file_exists($view = core::path() . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . $route . DIRECTORY_SEPARATOR . 'index.html')) {
|
||||
include $view;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать свойство
|
||||
*
|
||||
* @param mixed $name Название
|
||||
* @param mixed $value Значение
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __set($name, $value): void
|
||||
{
|
||||
if ($name === 'model') {
|
||||
if (!isset($this->model)) {
|
||||
$this->model = $value;
|
||||
return;
|
||||
} else {
|
||||
throw new Exception('Запрещено переопределять модель');
|
||||
}
|
||||
} else if ($name === 'view') {
|
||||
if (!isset($this->view)) {
|
||||
$this->view = $value;
|
||||
return;
|
||||
} else {
|
||||
throw new Exception('Запрещено переопределять шаблонизатор представления');
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception('Свойство не найдено: ' . $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать свойство
|
||||
*
|
||||
* @param mixed $name Название
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get($name)
|
||||
{
|
||||
if ($name === 'model') {
|
||||
if (isset($this->model)) {
|
||||
// Если модель найдена
|
||||
return $this->model;
|
||||
} else {
|
||||
// Инициализация класса модели
|
||||
$model = preg_replace('/' . core::controllerPostfix() . '$/i', '', basename(get_class($this))) . core::modelPostfix();
|
||||
// Иначе
|
||||
if (class_exists($model_class = core::namespace() . '\\models\\' . $model)) {
|
||||
// Если найдена одноимённая с контроллером модель (без постфикса)
|
||||
return $this->model = new $model_class;
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else if ($name === 'view') {
|
||||
if (isset($this->view)) {
|
||||
// Если модель найдена
|
||||
return $this->view;
|
||||
} else {
|
||||
$path = core::path() . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'views';
|
||||
$loader = new FilesystemLoader($path);
|
||||
|
||||
return $this->view = (new view($loader, [
|
||||
// 'cache' => $path . DIRECTORY_SEPARATOR . 'cache',
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception('Свойство не найдено: ' . $name);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Проверить свойство на инициализированность
|
||||
*
|
||||
* @param string $name Название
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function __isset(string $name)
|
||||
{
|
||||
if ($name === 'model') {
|
||||
return isset($this->model);
|
||||
} else if ($name === 'view') {
|
||||
return isset($this->view);
|
||||
}
|
||||
|
||||
throw new Exception('Свойство не найдено: ' . $name);
|
||||
}
|
||||
}
|
505
mirzaev/minimal/system/core.php
Normal file → Executable file
505
mirzaev/minimal/system/core.php
Normal file → Executable file
@@ -1,141 +1,364 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal;
|
||||
|
||||
use mirzaev\minimal\router;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Ядро
|
||||
*
|
||||
* @package mirzaev\minimal
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
final class core
|
||||
{
|
||||
/**
|
||||
* @var PDO $db Соединение с базой данных
|
||||
*/
|
||||
private static PDO $db;
|
||||
|
||||
/**
|
||||
* @var router $router Маршрутизатор
|
||||
*/
|
||||
private static router $router;
|
||||
|
||||
/**
|
||||
* @var string $path Корневая директория
|
||||
*/
|
||||
private static string $path;
|
||||
|
||||
/**
|
||||
* @var string $namespace Пространство имён
|
||||
*/
|
||||
private static string $namespace;
|
||||
|
||||
/**
|
||||
* @var string $postfix_controller Постфикс контроллеров
|
||||
*/
|
||||
private static string $postfix_controller = '_controller';
|
||||
|
||||
/**
|
||||
* @var string $postfix_model Постфикс моделей
|
||||
*/
|
||||
private static string $postfix_model = '_model';
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param string $db
|
||||
* @param string $login
|
||||
* @param string $password
|
||||
* @param router $router Маршрутизатор
|
||||
*/
|
||||
public function __construct(string $db = 'mysql:dbname=db;host=127.0.0.1', string $login = '', string $password = '', router $router = null)
|
||||
{
|
||||
// Инициализация маршрутизатора
|
||||
self::$router = $router ?? new router;
|
||||
|
||||
// Инициализация корневого пространства имён
|
||||
self::$namespace = __NAMESPACE__;
|
||||
|
||||
try {
|
||||
// Инициализация PDO
|
||||
self::$db = new PDO($db, $login, $password);
|
||||
} catch (PDOException $e) {
|
||||
throw new Exception('Проблемы при соединении с базой данных: ' . $e->getMessage(), $e->getCode());
|
||||
}
|
||||
|
||||
// Обработка запроса
|
||||
self::$router::handle();
|
||||
}
|
||||
|
||||
/**
|
||||
* Деструктор
|
||||
*
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
// Закрытие соединения
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать/записать корневую директорию
|
||||
*
|
||||
* @var string|null $path Путь
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public static function path(string $path = null): string
|
||||
{
|
||||
return self::$path = (string) ($path ?? self::$path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать/записать соединение с базой данных
|
||||
*
|
||||
* @var PDO|null $db Соединение с базой данных
|
||||
*
|
||||
* @return PDO
|
||||
*/
|
||||
public static function db(PDO $db = null): PDO
|
||||
{
|
||||
return self::$db = $db ?? self::$db;
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать постфикс контроллеров
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public static function controllerPostfix(): ?string
|
||||
{
|
||||
return self::$postfix_controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать постфикс моделей
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public static function modelPostfix(): ?string
|
||||
{
|
||||
return self::$postfix_model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать пространство имён
|
||||
*
|
||||
* @return string|null
|
||||
*/
|
||||
public static function namespace(): ?string
|
||||
{
|
||||
return self::$namespace;
|
||||
}
|
||||
}
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal;
|
||||
|
||||
// Files of the project
|
||||
use mirzaev\minimal\router,
|
||||
mirzaev\minimal\route,
|
||||
mirzaev\minimal\controller,
|
||||
mirzaev\minimal\model;
|
||||
|
||||
// Built-in libraries
|
||||
use exception,
|
||||
BadMethodCallException as exception_method,
|
||||
DomainException as exception_domain,
|
||||
InvalidArgumentException as exception_argument,
|
||||
UnexpectedValueException as exception_value,
|
||||
ReflectionClass as reflection;
|
||||
|
||||
/**
|
||||
* Core
|
||||
*
|
||||
* @param string $namespace Namespace where the core was initialized from
|
||||
* @param controller $controller An instance of the controller
|
||||
* @param model $model An instance of the model
|
||||
* @param router $router An instance of the router
|
||||
*
|
||||
* @mathod self __construct(?string $namespace) Constructor
|
||||
* @method void __destruct() Destructor
|
||||
* @method string|null request(?string $uri, ?string $method, array $variabls) Handle the request
|
||||
* @method string|null route(route $route, string $method) Handle the route
|
||||
*
|
||||
* @package mirzaev\minimal
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
final class core
|
||||
{
|
||||
/**
|
||||
* Namespace
|
||||
*
|
||||
* @var string $namespace Namespace where the core was initialized from
|
||||
*
|
||||
* @see https://www.php-fig.org/psr/psr-4/
|
||||
*/
|
||||
public string $namespace {
|
||||
// Read
|
||||
get => $this->namespace;
|
||||
}
|
||||
|
||||
/**
|
||||
* Controller
|
||||
*
|
||||
* @var controller $controller An instance of the controller
|
||||
*/
|
||||
private controller $controller {
|
||||
// Read
|
||||
get => $this->controller ??= new controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* Model
|
||||
*
|
||||
* @var model $model An instance of the model
|
||||
*/
|
||||
private model $model {
|
||||
// Read
|
||||
get => $this->model ??= new model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Router
|
||||
*
|
||||
* @var router $router An instance of the router
|
||||
*/
|
||||
public router $router {
|
||||
get => $this->router ??= router::initialize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constrictor
|
||||
*
|
||||
* @param ?string $namespace Пространство имён системного ядра
|
||||
*
|
||||
* @return self The instance of the core
|
||||
*/
|
||||
public function __construct(
|
||||
?string $namespace = null
|
||||
) {
|
||||
// Writing a namespace to the property
|
||||
$this->namespace = $namespace ?? (new reflection(self::class))->getNamespaceName();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Destructor
|
||||
*/
|
||||
public function __destruct() {}
|
||||
|
||||
/**
|
||||
* Request
|
||||
*
|
||||
* Handle the request
|
||||
*
|
||||
* @param string|null $uri URI of the request (value by default: $_SERVER['REQUEST_URI'])
|
||||
* @param string|null $method Method of the request (GET, POST, PUT...) (value by default: $_SERVER["REQUEST_METHOD"])
|
||||
* @paam array $parameters parameters for merging with route parameters
|
||||
*
|
||||
* @return string|null Response
|
||||
*/
|
||||
public function request(?string $uri = null, ?string $method = null, array $parameters = []): ?string
|
||||
{
|
||||
// Matching a route
|
||||
$route = $this->router->match($uri ??= $_SERVER['REQUEST_URI'] ?? '/', $method ??= $_SERVER["REQUEST_METHOD"]);
|
||||
|
||||
if ($route) {
|
||||
// Initialized the route
|
||||
|
||||
if (!empty($parameters)) {
|
||||
// Recaived parameters
|
||||
|
||||
// Merging parameters with route parameters
|
||||
$route->parameters = $parameters + $route->parameters;
|
||||
}
|
||||
|
||||
// Handling the route and exit (success)
|
||||
return $this->route($route, $method);
|
||||
}
|
||||
|
||||
// Exit (fail)
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Route
|
||||
*
|
||||
* Handle the route
|
||||
*
|
||||
* @param route $route The route
|
||||
* @param string $method Method of requests (GET, POST, PUT, DELETE, COOKIE...)
|
||||
*
|
||||
* @return string|null Response, if generated
|
||||
*/
|
||||
public function route(route $route, string $method = 'GET'): ?string
|
||||
{
|
||||
// Initializing name of the controller class
|
||||
$controller = $route->controller;
|
||||
|
||||
if ($route->controller instanceof controller) {
|
||||
// Initialized the controller
|
||||
} else if (class_exists($controller = "$this->namespace\\controllers\\$controller")) {
|
||||
// Found the controller by its name
|
||||
|
||||
// Initializing the controller
|
||||
$route->controller = new $controller(core: $this);
|
||||
} else if (!empty($route->controller)) {
|
||||
// Not found the controller and $route->controller has a value
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception_domain('Failed to found the controller: ' . $route->controller);
|
||||
} else {
|
||||
// Not found the controller and $route->controller is empty
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception_argument('Failed to initialize the controller: ' . $route->controller);
|
||||
}
|
||||
|
||||
// Deinitializing name of the controller class
|
||||
unset($controller);
|
||||
|
||||
// Initializing name if the model class
|
||||
$model = $route->model;
|
||||
|
||||
if ($route->model instanceof model) {
|
||||
// Initialized the model
|
||||
} else if (class_exists($model = "$this->namespace\\models\\$model")) {
|
||||
// Found the model by its name
|
||||
|
||||
// Initializing the model
|
||||
$route->model = new $model;
|
||||
} else if (!empty($route->model)) {
|
||||
// Not found the model and $route->model has a value
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception_domain('Failed to initialize the model: ' . ($route->model ?? $route->controller));
|
||||
}
|
||||
|
||||
// Deinitializing name of the model class
|
||||
unset($model);
|
||||
|
||||
if ($route->model instanceof model) {
|
||||
// Initialized the model
|
||||
|
||||
// Writing the model to the controller
|
||||
$route->controller->model = $route->model;
|
||||
}
|
||||
|
||||
if ($method === 'POST') {
|
||||
// POST
|
||||
|
||||
if (method_exists($route->controller, $route->method)) {
|
||||
// Found the method of the controller
|
||||
|
||||
// Executing method of the controller that handles the route and exit (success)
|
||||
return $route->controller->{$route->method}($route->parameters + $_POST, $_FILES);
|
||||
} else {
|
||||
// Not found the method of the controller
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Failed to find the method of the controller: ' . $route->method);
|
||||
}
|
||||
} else if ($method === 'GET') {
|
||||
// GET
|
||||
|
||||
if (method_exists($route->controller, $route->method)) {
|
||||
// Found the method of the controller
|
||||
|
||||
if ($_SERVER["CONTENT_TYPE"] === 'multipart/form-data' || $_SERVER["CONTENT_TYPE"] === 'application/x-www-form-urlencoded') {
|
||||
// The requeset content type is the "multipart/form-data" or "application/x-www-form-urlencoded"
|
||||
|
||||
// Analysis of the request
|
||||
[$_GET, $_FILES] = request_parse_body($route->options);
|
||||
}
|
||||
|
||||
// Executing method of the controller that handles the route and exit (success)
|
||||
return $route->controller->{$route->method}($route->parameters + $_GET, $_FILES);
|
||||
} else {
|
||||
// Not found the method of the controller
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Failed to find the method of the controller: ' . $route->method);
|
||||
}
|
||||
} else if ($method === 'PUT') {
|
||||
// PUT
|
||||
|
||||
if (method_exists($route->controller, $route->method)) {
|
||||
// Found the method of the controller
|
||||
|
||||
if ($_SERVER["CONTENT_TYPE"] === 'multipart/form-data' || $_SERVER["CONTENT_TYPE"] === 'application/x-www-form-urlencoded') {
|
||||
// The requeset content type is the "multipart/form-data" or "application/x-www-form-urlencoded"
|
||||
|
||||
// Analysis of the request
|
||||
[$_PUT, $_FILES] = request_parse_body($route->options);
|
||||
}
|
||||
|
||||
// Executing method of the controller that handles the route and exit (success)
|
||||
return $route->controller->{$route->method}($route->parameters + $_PUT, $_FILES);
|
||||
} else {
|
||||
// Not found the method of the controller
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Failed to find the method of the controller: ' . $route->method);
|
||||
}
|
||||
} else if ($method === 'DELETE') {
|
||||
// DELETE
|
||||
|
||||
if (method_exists($route->controller, $route->method)) {
|
||||
// Found the method of the controller
|
||||
|
||||
if ($_SERVER["CONTENT_TYPE"] === 'multipart/form-data' || $_SERVER["CONTENT_TYPE"] === 'application/x-www-form-urlencoded') {
|
||||
// The requeset content type is the "multipart/form-data" or "application/x-www-form-urlencoded"
|
||||
|
||||
// Analysis of the request
|
||||
[$_DELETE, $_FILES] = request_parse_body($route->options);
|
||||
}
|
||||
|
||||
// Executing method of the controller that handles the route and exit (success)
|
||||
return $route->controller->{$route->method}($route->parameters + $_DELETE, $_FILES);
|
||||
} else {
|
||||
// Not found the method of the controller
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Failed to find the method of the controller: ' . $route->method);
|
||||
}
|
||||
} else if ($method === 'PATCH') {
|
||||
// PATCH
|
||||
|
||||
if (method_exists($route->controller, $route->method)) {
|
||||
// Found the method of the controller
|
||||
|
||||
if ($_SERVER["CONTENT_TYPE"] === 'multipart/form-data' || $_SERVER["CONTENT_TYPE"] === 'application/x-www-form-urlencoded') {
|
||||
// The requeset content type is the "multipart/form-data" or "application/x-www-form-urlencoded"
|
||||
|
||||
// Analysis of the request
|
||||
[$_PATCH, $_FILES] = request_parse_body($route->options);
|
||||
}
|
||||
|
||||
// Executing method of the controller that handles the route and exit (success)
|
||||
return $route->controller->{$route->method}($route->parameters + $_PATCH, $_FILES);
|
||||
} else {
|
||||
// Not found the method of the controller
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Failed to find the method of the controller: ' . $route->method);
|
||||
}
|
||||
} else if ($method === 'HEAD') {
|
||||
// HEAD
|
||||
|
||||
if (method_exists($route->controller, $route->method)) {
|
||||
// Found the method of the controller
|
||||
|
||||
// Executing method of the controller that handles the route and exit (success)
|
||||
return $route->controller->{$route->method}($route->parameters);
|
||||
} else {
|
||||
// Not found the method of the controller
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Failed to find the method of the controller: ' . $route->method);
|
||||
}
|
||||
} else if ($method === 'OPTIONS') {
|
||||
// OPTIONS
|
||||
|
||||
if (method_exists($route->controller, $route->method)) {
|
||||
// Found the method of the controller
|
||||
|
||||
// Executing method of the controller that handles the route and exit (success)
|
||||
return $route->controller->{$route->method}($route->parameters);
|
||||
} else {
|
||||
// Not found the method of the controller
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Failed to find the method of the controller: ' . $route->method);
|
||||
}
|
||||
} else if ($method === 'CONNECT') {
|
||||
// CONNECT
|
||||
|
||||
if (method_exists($route->controller, $route->method)) {
|
||||
// Found the method of the controller
|
||||
|
||||
// Executing method of the controller that handles the route and exit (success)
|
||||
return $route->controller->{$route->method}($route->parameters);
|
||||
} else {
|
||||
// Not found the method of the controller
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Failed to find the method of the controller: ' . $route->method);
|
||||
}
|
||||
} else if ($method === 'TRACE') {
|
||||
// TRACE
|
||||
|
||||
if (method_exists($route->controller, $route->method)) {
|
||||
// Found the method of the controller
|
||||
|
||||
// Executing method of the controller that handles the route and exit (success)
|
||||
return $route->controller->{$route->method}($route->parameters);
|
||||
} else {
|
||||
// Not found the method of the controller
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Failed to find the method of the controller: ' . $route->method);
|
||||
}
|
||||
} else {
|
||||
// Not recognized method of the request
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception_value('Failed to recognize the method: ' . $method);
|
||||
}
|
||||
|
||||
// Exit (fail)
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
30
mirzaev/minimal/system/model.php
Executable file
30
mirzaev/minimal/system/model.php
Executable file
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal;
|
||||
|
||||
// Files of the project
|
||||
use mirzaev\minimal\traits\magic;
|
||||
|
||||
/**
|
||||
* Model
|
||||
*
|
||||
* @method self __construct() Constructor
|
||||
*
|
||||
* @package mirzaev\minimal
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
class model
|
||||
{
|
||||
use magic;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function __construct() {}
|
||||
}
|
@@ -1,90 +0,0 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal\models;
|
||||
|
||||
use mirzaev\minimal\core;
|
||||
|
||||
use PDO;
|
||||
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* Модель
|
||||
*
|
||||
* @package mirzaev\minimal\models
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
class model
|
||||
{
|
||||
/**
|
||||
* @var PDO $db Соединение с базой данных
|
||||
*/
|
||||
protected PDO $db;
|
||||
|
||||
/**
|
||||
* Конструктор
|
||||
*
|
||||
* @param PDO|null $db Соединение с базой данных
|
||||
*/
|
||||
public function __construct(PDO $db = null)
|
||||
{
|
||||
$this->db = $db ?? core::db();
|
||||
}
|
||||
|
||||
/**
|
||||
* Записать свойство
|
||||
*
|
||||
* @param mixed $name Название
|
||||
* @param mixed $value Значение
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __set($name, $value): void
|
||||
{
|
||||
if ($name === 'db') {
|
||||
if (!isset($this->db)) {
|
||||
$this->db = $value;
|
||||
return;
|
||||
} else {
|
||||
throw new Exception('Запрещено переопределять соединение с базой данных');
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception('Свойство не найдено: ' . $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Прочитать свойство
|
||||
*
|
||||
* @param mixed $name Название
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function __get($name)
|
||||
{
|
||||
if ($name === 'db') {
|
||||
return $this->db;
|
||||
}
|
||||
|
||||
throw new Exception('Свойство не найдено: ' . $name);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Проверить свойство на инициализированность
|
||||
*
|
||||
* @param string $name Название
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function __isset(string $name)
|
||||
{
|
||||
if ($name === 'db') {
|
||||
return isset($this->db);
|
||||
}
|
||||
|
||||
throw new Exception('Свойство не найдено: ' . $name);
|
||||
}
|
||||
}
|
127
mirzaev/minimal/system/route.php
Executable file
127
mirzaev/minimal/system/route.php
Executable file
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal;
|
||||
|
||||
/**
|
||||
* Route
|
||||
*
|
||||
* @param string|controller $controller Name of the controller
|
||||
* @param string $method Name of the method of the method of $this->controller
|
||||
* @param string|model $model Name of the model
|
||||
* @param array $parameters Arguments for the $this->method (will be concatenated together with generated request parameters)
|
||||
* @param array $options Options for `request_parse_body($options)`
|
||||
*
|
||||
* @method self __construct(string $controller,?string $method, ?string $model, array $variables, array $options) Constructor
|
||||
*
|
||||
* @package mirzaev\minimal
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
final class route
|
||||
{
|
||||
/**
|
||||
* Controller
|
||||
*
|
||||
* @var string|model $controller Name of the controller or an instance of the controller
|
||||
*/
|
||||
public string|controller $controller {
|
||||
// Read
|
||||
get => $this->controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* Method
|
||||
*
|
||||
* @var string $method Name of the method of the method of $this->controller
|
||||
*/
|
||||
public string $method{
|
||||
// Read
|
||||
get => $this->method;
|
||||
}
|
||||
|
||||
/**
|
||||
* Model
|
||||
*
|
||||
* @var string|model|null $model Name of the model of an instance of the model
|
||||
*/
|
||||
public string|model|null $model {
|
||||
// Read
|
||||
get => $this->model;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parameters
|
||||
*
|
||||
* @var array $parameters Arguments for the $this->method (will be concatenated together with generated request parameters)
|
||||
*/
|
||||
public array $parameters {
|
||||
// Read
|
||||
get => $this->parameters;
|
||||
}
|
||||
|
||||
/**
|
||||
* Options
|
||||
*
|
||||
* Used only for GET, PUT, PATCH and DELETE
|
||||
*
|
||||
* @var string $options Options for `request_parse_body($options)`
|
||||
*/
|
||||
public array $options {
|
||||
// Write
|
||||
set (array $value) => array_filter(
|
||||
$value,
|
||||
fn(string $key) => match ($key) {
|
||||
'post_max_size',
|
||||
'max_input_vars',
|
||||
'max_multipart_body_parts',
|
||||
'max_file_uploads',
|
||||
'upload_max_filesize' => true,
|
||||
default => false
|
||||
},
|
||||
ARRAY_FILTER_USE_KEY
|
||||
);
|
||||
|
||||
// Read
|
||||
get => $this->options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
*
|
||||
* @param string|controller $controller Name of the controller
|
||||
* @param string|null $method Name of the method of the method of $controller
|
||||
* @param string|model|null $model Name of the model
|
||||
* @param array $parameters Arguments for the $method (will be concatenated together with generated request parameters)
|
||||
* @param array $options Options for `request_parse_body` (Only for POST method)
|
||||
*
|
||||
* @return self
|
||||
*/
|
||||
public function __construct(
|
||||
string|controller $controller,
|
||||
?string $method = 'index',
|
||||
string|model|null $model = null,
|
||||
array $parameters = [],
|
||||
array $options = []
|
||||
) {
|
||||
// Writing name of the controller
|
||||
$this->controller = $controller;
|
||||
|
||||
// Writing name of the model
|
||||
$this->model = $model;
|
||||
|
||||
// Writing name of the method of the controller
|
||||
$this->method = $method;
|
||||
|
||||
// Writing parameters
|
||||
$this->parameters = $parameters;
|
||||
|
||||
// Writing options
|
||||
if (match ($method) {
|
||||
'GET', 'PUT', 'PATCH', 'DELETE' => true,
|
||||
default => false
|
||||
}) $this->options = $options;
|
||||
}
|
||||
}
|
407
mirzaev/minimal/system/router.php
Normal file → Executable file
407
mirzaev/minimal/system/router.php
Normal file → Executable file
@@ -1,122 +1,285 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal;
|
||||
|
||||
use mirzaev\shop\core;
|
||||
|
||||
/**
|
||||
* Маршрутизатор
|
||||
*
|
||||
* @package mirzaev\shop
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
final class router
|
||||
{
|
||||
/**
|
||||
* @var array $router Маршруты
|
||||
*/
|
||||
public static array $routes = [];
|
||||
|
||||
/**
|
||||
* Новый маршрут
|
||||
*
|
||||
* @param string $route Маршрут
|
||||
* @param string $controller Контроллер
|
||||
* @param string|null $method Метод
|
||||
* @param string|null $type Тип
|
||||
* @param string|null $model Модель
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function create(string $route, string $controller, string $method = null, string $type = 'GET', string $model = null): void
|
||||
{
|
||||
if (is_null($model)) {
|
||||
$model = $controller;
|
||||
}
|
||||
|
||||
self::$routes[$route][$type] = [
|
||||
// Инициализация контроллера с постфиксом
|
||||
'controller' => preg_match('/' . core::controllerPostfix() . '$/i', $controller) ? $controller : $controller . core::controllerPostfix(),
|
||||
'model' => preg_match('/' . core::modelPostfix() . '$/i', $model) ? $model : $model . core::modelPostfix(),
|
||||
'method' => $method ?? '__construct'
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Обработка маршрута
|
||||
*
|
||||
* @param string $route Маршрут
|
||||
* @param string $controller Контроллер
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function handle(string $uri = null): void
|
||||
{
|
||||
// Если не передан URI, то взять из данных веб-сервера
|
||||
$uri = $uri ?? $_SERVER['REQUEST_URI'] ?? '';
|
||||
|
||||
// Инициализация URL
|
||||
$url = parse_url($uri, PHP_URL_PATH);
|
||||
|
||||
// Сортировка массива маршрутов от большего ключа к меньшему
|
||||
krsort(self::$routes);
|
||||
|
||||
foreach (self::$routes as $key => $value) {
|
||||
// Если не записан "/" в начале, то записать
|
||||
$route_name = preg_replace('/^([^\/])/', '/$1', $key);
|
||||
$url = preg_replace('/^([^\/])/', '/$1', $url);
|
||||
|
||||
// Если не записан "/" в конце, то записать
|
||||
$route_name = preg_replace('/([^\/])$/', '$1/', $route_name);
|
||||
$url = preg_replace('/([^\/])$/', '$1/', $url);
|
||||
|
||||
if (mb_stripos($route_name, $url, 0, "UTF-8") === 0 && mb_strlen($route_name, 'UTF-8') <= mb_strlen($url, 'UTF-8')) {
|
||||
// Если найден маршрут, а так же его длина не меньше длины запрошенного URL
|
||||
$route = $value[$_SERVER["REQUEST_METHOD"] ?? 'GET'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($route)) {
|
||||
// Если маршрут найден
|
||||
if (class_exists($controller_class = core::namespace() . '\\controllers\\' . $route['controller'])) {
|
||||
// Если найден класс-контроллер маршрута
|
||||
|
||||
$controller = new $controller_class;
|
||||
|
||||
if (empty($response = $controller->{$route['method']}($_REQUEST))) {
|
||||
// Если не получен ответ после обработки контроллера
|
||||
|
||||
// Удаление постфикса для поиска директории
|
||||
$dir = preg_replace('/' . core::controllerPostfix() . '$/i', '', $route['controller']);
|
||||
|
||||
// Отрисовка шаблона по умолчанию
|
||||
$response = $controller->view($dir);
|
||||
}
|
||||
|
||||
echo $response;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
echo self::error();
|
||||
}
|
||||
|
||||
private static function error(): ?string
|
||||
{
|
||||
if (
|
||||
class_exists($class = core::namespace() . '\\controllers\\errors' . core::controllerPostfix()) &&
|
||||
method_exists($class, $method = 'error404')
|
||||
) {
|
||||
// Если существует контроллер ошибок и метод-обработчик ответа 404,
|
||||
// то вызвать обработку ответа 404
|
||||
return (new $class(basename($class)))->$method();
|
||||
} else {
|
||||
// Никаких исключений не вызывать, отдать пустую страницу
|
||||
// Либо можно, но отображать в зависимости от включенного дебаг режима
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal;
|
||||
|
||||
// Files of the project
|
||||
use mirzaev\minimal\route,
|
||||
mirzaev\minimal\traits\singleton;
|
||||
|
||||
// Build-ing libraries
|
||||
use InvalidArgumentException as exception_argument;
|
||||
|
||||
/**
|
||||
* Router
|
||||
*
|
||||
* @param array $routes The registry of routes
|
||||
*
|
||||
* @method self write(string $uri, string $method)
|
||||
* @method self sort() Sort routes (DEV)
|
||||
* @method string universalize(string $urn) Universalize URN
|
||||
*
|
||||
* @package mirzaev\minimal
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
final class router
|
||||
{
|
||||
use singleton;
|
||||
|
||||
/**
|
||||
* Routes
|
||||
*
|
||||
* @var array $routes The registry of routes
|
||||
*/
|
||||
protected array $routes = [];
|
||||
|
||||
/**
|
||||
* Write a route
|
||||
*
|
||||
* @param string $urn URN of the route ('/', '/page', '/page/$variable', '/page/$collector...'...)
|
||||
* @param route $route The route
|
||||
* @param string|array $method Method of requests (GET, POST, PUT, DELETE, COOKIE...)
|
||||
*
|
||||
* @return self The instance from which the method was called (fluent interface)
|
||||
*/
|
||||
public function write(
|
||||
string $urn,
|
||||
route $route,
|
||||
null|string|array $method = 'GET'
|
||||
): self {
|
||||
foreach (is_array($method) ? $method : [$method] as $method) {
|
||||
// Iterate over methods of requests
|
||||
|
||||
// Validating method
|
||||
$method = match ($method) {
|
||||
'POST', 'GET', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'CONNECT', 'TRACE' => $method,
|
||||
default => throw new exception_argument("Failed to initialize method: \"$method\"")
|
||||
};
|
||||
|
||||
// Writing to the registry of routes
|
||||
$this->routes[$urn][$method] = $route;
|
||||
}
|
||||
|
||||
// Exit (success) (fluent interface)
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Match
|
||||
*
|
||||
* Match request URI with registry of routes
|
||||
*
|
||||
* @param string $uri URI (protocol://domain/foo/bar)
|
||||
* @param string $method Method of the request (GET, POST, PUT...)
|
||||
*
|
||||
* @return route|null Route, if found
|
||||
*/
|
||||
public function match(string $uri, string $method): ?route {
|
||||
// Declaration of the registry of routes directoies
|
||||
$routes = [];
|
||||
|
||||
foreach ($this->routes as $route => $data) {
|
||||
// Iteration over routes
|
||||
|
||||
// Search directories of route (explode() creates empty value in array)
|
||||
preg_match_all('/(^\/$|[^\/]+)/', $route, $data['directories']);
|
||||
$routes[$route] = $data['directories'][0];
|
||||
}
|
||||
|
||||
if (count($routes) === count($this->routes)) {
|
||||
// Initialized the registry of routes directoies
|
||||
|
||||
// Universalization of URN (/foo/bar)
|
||||
$urn = self::universalize(parse_url(urldecode($uri), PHP_URL_PATH));
|
||||
|
||||
// Search directories of URN (explode() creates empty value in array)
|
||||
preg_match_all('/(^\/$|[^\/]+)/', $urn, $directories);
|
||||
$directories = $directories[0];
|
||||
|
||||
/**
|
||||
* Initialization of the route
|
||||
*/
|
||||
|
||||
// Initializing the buffer of matches of route directories with URN directories
|
||||
$matches = [];
|
||||
|
||||
foreach ($directories as $i => $urn_directory) {
|
||||
// Iteration over directories of URN
|
||||
|
||||
foreach ($this->routes as $route => $data) {
|
||||
// Iteration over routes
|
||||
|
||||
if (isset($data[$method])) {
|
||||
// The request method matches the route method
|
||||
|
||||
// Universalization of route
|
||||
$route = self::universalize($route);
|
||||
|
||||
// Skipping unmatched routes based on results of previous iterations
|
||||
if (isset($matches[$route]) && $matches[$route] === false) continue;
|
||||
|
||||
// Initializing of route directory
|
||||
$route_directory = $routes[$route][$i] ?? null;
|
||||
|
||||
if (isset($route_directory)) {
|
||||
// Initialized of route directory
|
||||
|
||||
if ($urn_directory === $route_directory) {
|
||||
// The directory of URN is identical to the directory of route
|
||||
|
||||
// Writing: end of URN directories XNOR end of route directories
|
||||
$matches[$route] = !(isset($directories[$_i = $i + 1]) xor isset($routes[$route][$_i]));
|
||||
} else if (preg_match('/^\$([a-zA-Z_\x80-\xff]+)$/', $route_directory) === 1) {
|
||||
// The directory of route is a variable ($variable)
|
||||
|
||||
// Writing: end of URN directories XNOR end of route directories
|
||||
$matches[$route] = !(isset($directories[$_i = $i + 1]) xor isset($routes[$route][$_i]));
|
||||
} else if (
|
||||
!isset($routes[$route][$i + 1])
|
||||
&& preg_match('/^\$([a-zA-Z_\x80-\xff]+\.\.\.)$/', $route_directory) === 1
|
||||
) {
|
||||
// The directory of route is a collector ($variable...)
|
||||
// AND this is the end of route directories
|
||||
|
||||
// Writing
|
||||
$matches[$route] = 'collector';
|
||||
} else $matches[$route] = false;
|
||||
} else if ($matches[$route] === 'collector') {
|
||||
} else $matches[$route] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finding a priority route from match results
|
||||
foreach ($matches as $route => $match) if ($match !== false) break;
|
||||
|
||||
if ($route && !empty($data = $this->routes[$route])) {
|
||||
// Route found
|
||||
|
||||
// Universalization of route
|
||||
$route = self::universalize($route);
|
||||
|
||||
/**
|
||||
* Initialization of route variables
|
||||
*/
|
||||
|
||||
foreach ($routes[$route] as $i => $route_directory) {
|
||||
// Iteration over directories of route
|
||||
|
||||
if (preg_match('/^\$([a-zA-Z_\x80-\xff]+)$/', $route_directory) === 1) {
|
||||
// The directory is a variable ($variable)
|
||||
|
||||
// Запись в реестр переменных и перещапись директории в маршруте
|
||||
$data[$method]->variables[trim($route_directory, '$')] = $directories[$i];
|
||||
} else if (preg_match('/^\$([a-zA-Z_\x80-\xff]+\.\.\.)$/', $route_directory) === 1) {
|
||||
// The directory of route is a collector ($variable...)
|
||||
|
||||
// Инициализаия ссылки на массив сборщика
|
||||
$collector = &$data[$method]->variables[trim($route_directory, '$.')];
|
||||
|
||||
// Инициализаия массива сборщика
|
||||
$collector ??= [];
|
||||
|
||||
// Запись в реестр переменных
|
||||
$collector[] = $directories[$i];
|
||||
|
||||
foreach (array_slice($directories, ++$i, preserve_keys: true) as &$urn_directory) {
|
||||
// Перебор директорий URN
|
||||
|
||||
// Запись в реестр переменных
|
||||
$collector[] = $urn_directory;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Exit (success or fail)
|
||||
return $data[$method] ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
// Exit (fail)
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorting routes
|
||||
*
|
||||
* 1. Short routes
|
||||
* 2. Long routes
|
||||
* 3. Short routes with variables (position of variables from "right" to "left")
|
||||
* 4. Long routes with variables (position of variables from "right" to "left")
|
||||
* 5. Short routes with collector
|
||||
* 6. Long routes with collector
|
||||
* 7. Short routes with variables and collector (position of variables from "right" to "left" then by amount)
|
||||
* 8. Long routes with variables and collector (position of variables from "right" to "left")
|
||||
*
|
||||
* Добавить чтобы сначала текст потом переменная затем после переменной первыми тексты и в конце перменные опять и так рекурсивно
|
||||
*
|
||||
* @return self The instance from which the method was called (fluent interface)
|
||||
*
|
||||
* @todo ПЕРЕДЕЛАТЬ ПОЛНОСТЬЮ
|
||||
*/
|
||||
public function sort(): self
|
||||
{
|
||||
uksort($this->routes, function (string $a, string $b) {
|
||||
// Sorting routes
|
||||
|
||||
// Initialization of string lengths (multibyte-safe)
|
||||
$length = [
|
||||
$a => mb_strlen($a),
|
||||
$b => mb_strlen($b)
|
||||
];
|
||||
|
||||
// Initialization of the presence of variables
|
||||
$variables = [
|
||||
$a => preg_match('/\$([a-zA-Z_\x80-\xff]+)(\/|$)/', $a) === 1,
|
||||
$b => preg_match('/\$([a-zA-Z_\x80-\xff]+)(\/|$)/', $b) === 1
|
||||
];
|
||||
|
||||
// Initialization of the presence of collectors
|
||||
$collectors = [
|
||||
$a => preg_match('/\$([a-zA-Z_\x80-\xff]+)\.\.\.$/', $a) === 1,
|
||||
$b => preg_match('/\$([a-zA-Z_\x80-\xff]+)\.\.\.$/', $b) === 1
|
||||
];
|
||||
|
||||
|
||||
if ($variables[$a] && !$variables[$b]) return 1;
|
||||
else if (!$variables[$a] && $variables[$b]) return -1;
|
||||
else if ($variables[$a] && $variables[$b]) {
|
||||
} else if ($collectors[$a] && !$collectors[$b]) return 1;
|
||||
else if (!$collectors[$a] && $collectors[$b]) return -1;
|
||||
else {
|
||||
// NOR variables and XAND collectors (both are not found or both are found)
|
||||
|
||||
// The routes are the same length (no changes)
|
||||
if ($length[$a] === $length[$b]) return 0;
|
||||
|
||||
// The longer route moves to the end
|
||||
return $length[$a] > $length[$b] ? 1 : -1;
|
||||
}
|
||||
});
|
||||
|
||||
// Exit (success) (fluent interface)
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Universalize URN
|
||||
*
|
||||
* Always "/" at the beginning and never "/" at the end
|
||||
*
|
||||
* @param string $urn URN (/foo/bar)
|
||||
*
|
||||
* @return string Universalized URN
|
||||
*/
|
||||
private function universalize(string $urn): string
|
||||
{
|
||||
// Universalization of URN and exit (success)
|
||||
return (string) '/' . mb_trim($urn, '/');
|
||||
}
|
||||
}
|
||||
|
83
mirzaev/minimal/system/traits/magic.php
Executable file
83
mirzaev/minimal/system/traits/magic.php
Executable file
@@ -0,0 +1,83 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal\traits;
|
||||
|
||||
// Built-in libraries
|
||||
use exception;
|
||||
|
||||
/**
|
||||
* Trait of magical methods
|
||||
*
|
||||
* @method void __set(string $name, mixed $value) Write property
|
||||
* @method mixed __get(string $name) Read property
|
||||
* @method void __unset(string $name) Delete property
|
||||
* @method bool __isset(string $name) Check property for initialization
|
||||
*
|
||||
* @package mirzaev\minimal\traits
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
trait magic
|
||||
{
|
||||
/**
|
||||
* Write property
|
||||
*
|
||||
* @param string $name Name of the property
|
||||
* @param mixed $value Value of the property
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __set(string $name, mixed $value = null): void
|
||||
{
|
||||
match ($name) {
|
||||
default => throw new exception('Property "' . static::class . "::\$$name\" not found", 404)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Read property
|
||||
*
|
||||
* @param string $name Name of the property
|
||||
*
|
||||
* @return mixed Value of the property
|
||||
*/
|
||||
public function __get(string $name): mixed
|
||||
{
|
||||
return match ($name) {
|
||||
default => throw new exception('Property "' . static::class . "::\$$name\" not found", 404)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete property
|
||||
*
|
||||
* @param string $name Name of the property
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function __unset(string $name): void
|
||||
{
|
||||
match ($name) {
|
||||
default => (function () use ($name) {
|
||||
unset($this->{$name});
|
||||
})()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check property for initialization
|
||||
*
|
||||
* @param string $name Name of the property
|
||||
*
|
||||
* @return bool Is the property initialized?
|
||||
*/
|
||||
public function __isset(string $name): bool
|
||||
{
|
||||
return match ($name) {
|
||||
default => isset($this->{$name})
|
||||
};
|
||||
}
|
||||
}
|
85
mirzaev/minimal/system/traits/singleton.php
Normal file
85
mirzaev/minimal/system/traits/singleton.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace mirzaev\minimal\traits;
|
||||
|
||||
// Built-in libraries
|
||||
use exception;
|
||||
|
||||
/**
|
||||
* Trait of singleton
|
||||
*
|
||||
* @method static initialize() Initialize an instance
|
||||
*
|
||||
* @package mirzaev\minimal\traits
|
||||
*
|
||||
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
|
||||
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
|
||||
*/
|
||||
trait singleton
|
||||
{
|
||||
/**
|
||||
* Constructor (blocked)
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
final private function __construct()
|
||||
{
|
||||
// Initializing the indicator that an instance of static::class has already been initialized
|
||||
static $instance = false;
|
||||
|
||||
if ($instance) {
|
||||
// An instance of static has already been initialized
|
||||
|
||||
// Exit (fail)
|
||||
throw new exception('Has already been initialized an instance of the ' . static::class);
|
||||
}
|
||||
|
||||
// Writing the indicator that the instance of static been initialized
|
||||
$instance = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize an instance
|
||||
*
|
||||
* Create an instance of static::class, or return an already created static::class instance
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public static function initialize(): static
|
||||
{
|
||||
// Initialize the buffer of the instance of static::class
|
||||
static $instance;
|
||||
|
||||
// Exit (success)
|
||||
return $instance ??= new static;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clone (blocked)
|
||||
*/
|
||||
private function __clone()
|
||||
{
|
||||
// Exit (fail)
|
||||
throw new exception('Cloning is inadmissible');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep (blocked)
|
||||
*/
|
||||
public function __sleep()
|
||||
{
|
||||
// Exit (fail)
|
||||
throw new exception('Serialization is inadmissible');
|
||||
}
|
||||
|
||||
/**
|
||||
* Wake up (blocked)
|
||||
*/
|
||||
public function __wakeup()
|
||||
{
|
||||
// Exit (fail)
|
||||
throw new exception('Deserialisation is inadmissible');
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user