Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
strategy:
fail-fast: false
matrix:
php: ['8.1', '8.5']
php: ['8.1', '8.2', '8.3', '8.4', '8.5']
steps:
- name: Checkout
uses: actions/checkout@v7
Expand All @@ -31,11 +31,11 @@ jobs:
github-token: ${{ secrets.GITHUB_TOKEN }}
coverage: none

- name: Validate Composer manifest and lock
- name: Validate Composer manifest
run: composer validate --no-check-publish --no-interaction

- name: Install locked dependencies
run: composer install --prefer-dist --no-interaction --no-progress --no-scripts
- name: Resolve and install dependencies
run: composer update --prefer-dist --no-interaction --no-progress --no-scripts

- name: Check PHP syntax
run: find . -path './vendor' -prune -o -path './.git' -prune -o -name '*.php' -type f -print0 | xargs -0 -n1 php -l
Expand All @@ -48,3 +48,6 @@ jobs:
else
echo 'No test script is declared for this package.'
fi

- name: Audit dependencies
run: composer audit --abandoned=report
42 changes: 10 additions & 32 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,42 +5,20 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.0.0] - 2025-01-XX - LTS Release
## [Unreleased]

### Added
- Initial LTS release
- Full documentation
- Core Engine functionality
- Container-based dependency injection
- Configuration management system
- Request/Response handling
- Exception handling system
- Autoload system
- Bootstrap system
- Plugin system
- Context management
This development version migrates the Engine source to Localzet Server 7.1. It has not been published as a stable release.

### Changed
- Removed deprecated `#[\AllowDynamicProperties]` from Request and Response classes
- Improved type safety with strict types
- Enhanced error handling
- Requires `localzet/server:^7.1`; the latest published `v8.1.11` package still requires Server 4.
- Upgrades the logging contract to Monolog 3.
- Server-owned global `response()`, `json()`, and `redirect()` helpers now keep the Server 7 contract. Use `triangle_response()`, `triangle_json()`, and `triangle_redirect()` for the Engine behavior.
- Fiber-backed request context is isolated by the active Fiber across Server 7 event loops.

### Fixed
- Fixed version conflicts in composer.json
- Improved URI safety checks
- Enhanced input validation
- Prevented Composer autoload from redeclaring Server 7 global helpers.
- Kept Engine JSON responses encoded as strings when Server 7 is loaded first.
- Removed implicit nullable parameter deprecations reported by PHP 8.5.

### Security
- Enhanced input validation
- Improved URI safety checks
- Better exception handling in production mode

---

## [Unreleased]

### Planned
- Performance optimizations
- Additional helper functions
- Enhanced plugin system

- Strip CR and LF from redirect locations created by `triangle_redirect()`.
110 changes: 89 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,89 @@
<p align="center"><a href="https://www.localzet.com" target="_blank">
<img src="https://static.zorin.space/media/logos/LocalzetGroup.png" width="400">
</a></p>

<p align="center">
<a href="https://packagist.org/packages/triangle/engine">
<img src="https://img.shields.io/packagist/dt/triangle/engine?label=%D0%A1%D0%BA%D0%B0%D1%87%D0%B8%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F" alt="Скачивания">
</a>
<a href="https://github.com/Triangle-org/Engine">
<img src="https://img.shields.io/github/commit-activity/t/Triangle-org/Engine?label=%D0%9A%D0%BE%D0%BC%D0%BC%D0%B8%D1%82%D1%8B" alt="Коммиты">
</a>
<a href="https://packagist.org/packages/triangle/engine">
<img src="https://img.shields.io/packagist/v/triangle/engine?label=%D0%92%D0%B5%D1%80%D1%81%D0%B8%D1%8F" alt="Версия">
</a>
<a href="https://packagist.org/packages/triangle/engine">
<img src="https://img.shields.io/packagist/dependency-v/triangle/engine/php?label=PHP" alt="Версия PHP">
</a>
<a href="https://github.com/Triangle-org/Engine">
<img src="https://img.shields.io/github/license/Triangle-org/Engine?label=%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F" alt="Лицензия">
</a>
</p>
# Triangle Engine

Triangle Engine is the HTTP and application runtime layer used by Triangle Framework projects. It provides request and response objects, configuration and execution context, application bootstrap helpers, and adapters around Localzet Server.

This development source requires **PHP 8.1 or newer** and **Localzet Server compatible with `^7.1`**. It is not a standalone web server: the network listener, event loop, protocol handling, and process lifecycle belong to Localzet Server.

## Requirements

- PHP `^8.1`, `ext-intl`, and `ext-json`.
- `localzet/server:^7.1`.
- Monolog `^3.0` and PSR Container `^1.0` or `^2.0`.
- Symfony Cache and Translation `~6.4.0`.

The latest published package is `v8.1.11` and requires `localzet/server:^4`. This development source targets Server 7.1. The two versions are not interchangeable:

| Engine version | Server requirement | Status |
| --- | --- | --- |
| `v8.1.11` | `^4` | Published on Packagist |
| Development source | `^7.1` | Server 7 migration; not yet a compatible stable release |

Do not install the published `v8.1.11` into an application that uses Server 7.1. Inspect the selected packages before upgrading:

```sh
composer show triangle/engine
composer show localzet/server
```

For the current development source, configure the repository and install its development branch only in a development environment:

```sh
composer config repositories.triangle-engine vcs https://github.com/Triangle-org/Engine
composer require triangle/engine:dev-main@dev
```

When the compatible major release is published, use its stable version constraint for production.

## Main components

- `Triangle\Engine\Config` loads and reads application configuration.
- `Triangle\Engine\Context` stores values for the active Fiber or coroutine; call `Context::destroy()` when a request or task finishes.
- `Triangle\Engine\Request` and `Triangle\Engine\Response` adapt Localzet Server HTTP messages for Triangle applications.
- `support\App` assembles configured listeners and processes for a Triangle application.
- `Triangle\Exception` contains the framework exception types and rendering contracts.

Use the application bootstrap already provided by your Triangle project. Engine does not create a listener or choose a deployment topology on its own.

## Compatibility with Server 7.1

Server 7 defines global `response()`, `json()`, and `redirect()` helpers. Their names overlap with older Engine helpers but their return values and behavior differ. Engine now exposes explicit names for its own behavior:

| Helper | Engine behavior | With Server 7.1 loaded |
| --- | --- | --- |
| `triangle_response()` | Engine response envelope and content negotiation | Use this to retain Engine behavior |
| `triangle_json()` | Encodes a PHP value as a JSON string | Use this when a string is needed |
| `triangle_redirect()` | Returns `Triangle\Engine\Response` and strips CR/LF from the location | Use this when Engine's response type is required |
| `responseJson()` / `responseBlob()` | Build an Engine response | Keep using these helpers |

The unprefixed names resolve to Server's helpers when Server is loaded first. This source guards its optional legacy declarations so Composer autoload does not redeclare those functions. Update direct application calls to `response()`, `json()`, or `redirect()` when they relied on Engine-specific semantics.

### Migrating Engine 8 helper calls

| Engine 8 call | Engine 9 replacement | Return contract |
| --- | --- | --- |
| `json($data)` | `triangle_json($data)` | JSON string |
| `response($data, $status)` | `triangle_response($data, $status)` | Engine response envelope and content negotiation |
| `redirect($url, $status)` | `triangle_redirect($url, $status)` | `Triangle\Engine\Response` |

If the application needs a JSON HTTP response without the Engine envelope, use `responseJson($data, $status)`. Calls without the `triangle_` prefix now follow the Server 7 contract, so update the call site according to whether it needs a string, an Engine response, or a Server response.

The current `Context` implementation keys storage by the active PHP Fiber regardless of the selected event-loop class. This matters when asynchronous handlers interleave on Server 7's standard event loops.

## Tests

Install the development dependencies and run the declared PHPUnit suite:

```sh
composer install
composer test
```

The suite covers configuration, Fiber context isolation, Server 7 helper interoperability, and a real loopback HTTP request through Server 7 using the Engine request and response classes. It does not replace application-level tests for routing, middleware, storage, or deployment behavior.

## Documentation and support

- [Project source](https://github.com/Triangle-org/Engine)
- [Report a security issue](SECURITY.md)
- [Contribution guide](CONTRIBUTING.md)

Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved.
89 changes: 89 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Triangle Engine

Triangle Engine — слой HTTP и запуска приложений, используемый проектами Triangle Framework. Он предоставляет объекты запроса и ответа, конфигурацию и контекст выполнения, средства запуска приложения и адаптеры для Localzet Server.

Эта версия в разработке требует **PHP 8.1 или новее** и **Localzet Server, совместимый с `^7.1`**. Engine не является самостоятельным веб-сервером: сетевой listener, event loop, протоколы и жизненный цикл процессов обеспечивает Localzet Server.

## Требования

- PHP `^8.1`, расширения `ext-intl` и `ext-json`.
- `localzet/server:^7.1`.
- Monolog `^3.0` и PSR Container `^1.0` или `^2.0`.
- Symfony Cache и Translation `~6.4.0`.

Последняя опубликованная версия пакета — `v8.1.11`; она требует `localzet/server:^4`. В этой версии исходников выполняется переход на Server 7.1. Эти версии нельзя считать взаимозаменяемыми:

| Версия Engine | Требование к Server | Статус |
| --- | --- | --- |
| `v8.1.11` | `^4` | Опубликована в Packagist |
| Исходники в разработке | `^7.1` | Переход на Server 7; совместимый стабильный релиз ещё не выпущен |

Не устанавливайте опубликованную `v8.1.11` в приложение на Server 7.1. Перед обновлением проверьте фактически выбранные версии:

```sh
composer show triangle/engine
composer show localzet/server
```

Для проверки текущих исходников настройте репозиторий и подключите ветку разработки только в окружении разработки:

```sh
composer config repositories.triangle-engine vcs https://github.com/Triangle-org/Engine
composer require triangle/engine:dev-main@dev
```

После публикации совместимого основного релиза используйте его стабильное ограничение версии в production.

## Основные компоненты

- `Triangle\Engine\Config` загружает и читает конфигурацию приложения.
- `Triangle\Engine\Context` хранит значения для активного Fiber или coroutine; вызывайте `Context::destroy()` при завершении запроса или задачи.
- `Triangle\Engine\Request` и `Triangle\Engine\Response` адаптируют HTTP-сообщения Localzet Server для приложений Triangle.
- `support\App` собирает настроенные listeners и процессы приложения Triangle.
- `Triangle\Exception` содержит типы исключений и контракты их отображения.

Используйте bootstrap, который предоставляет ваш проект Triangle. Engine сам не создаёт listener и не выбирает схему развёртывания.

## Совместимость с Server 7.1

Server 7 определяет глобальные функции `response()`, `json()` и `redirect()`. Их имена пересекаются с прежними помощниками Engine, но значения и поведение отличаются. Для прежней семантики Engine доступны отдельные имена:

| Функция | Поведение Engine | При загрузке Server 7.1 |
| --- | --- | --- |
| `triangle_response()` | Обёртка ответа Engine и выбор JSON/HTML | Используйте для сохранения поведения Engine |
| `triangle_json()` | Кодирует значение PHP в строку JSON | Используйте, когда нужна именно строка |
| `triangle_redirect()` | Возвращает `Triangle\Engine\Response` и удаляет CR/LF из адреса | Используйте, когда нужен тип ответа Engine |
| `responseJson()` / `responseBlob()` | Создают ответ Engine | Можно продолжать использовать |

Если Server загружен первым, непомеченные префиксом функции относятся к Server. Исходники Engine защищают необязательные старые объявления от повторного определения при автозагрузке Composer. Если приложение рассчитывало на особенности `response()`, `json()` или `redirect()` из Engine, замените такие вызовы на соответствующие функции с префиксом `triangle_`.

### Переход с функций Engine 8

| Вызов в Engine 8 | Замена в Engine 9 | Тип результата |
| --- | --- | --- |
| `json($data)` | `triangle_json($data)` | Строка JSON |
| `response($data, $status)` | `triangle_response($data, $status)` | Обёртка ответа Engine и выбор JSON/HTML |
| `redirect($url, $status)` | `triangle_redirect($url, $status)` | `Triangle\Engine\Response` |

Если нужен JSON HTTP-ответ без обёртки Engine, используйте `responseJson($data, $status)`. Вызовы без префикса `triangle_` теперь следуют контракту Server 7. При обновлении выберите функцию по требуемому результату: строка JSON, ответ Engine или ответ Server.

Текущий `Context` выбирает ключ хранения по активному PHP Fiber независимо от выбранного event loop. Это важно, когда асинхронные обработчики Server 7 чередуются в стандартных циклах событий.

## Тесты

Установите зависимости для разработки и запустите объявленный набор PHPUnit:

```sh
composer install
composer test
```

Набор проверяет конфигурацию, изоляцию контекста Fiber, взаимодействие с помощниками Server 7 и реальный HTTP-запрос через loopback-сокет с классами запроса и ответа Engine. Он не заменяет тесты приложения для маршрутизации, middleware, хранилищ и поведения при развёртывании.

## Документация и поддержка

- [Исходный код проекта](https://github.com/Triangle-org/Engine)
- [Сообщить об уязвимости](SECURITY.md)
- [Правила участия](CONTRIBUTING.md)

Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved.
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
"php": "^8.1",
"ext-intl": "*",
"ext-json": "*",
"localzet/server": "^4",
"monolog/monolog": "^2.0",
"localzet/server": "^7.1",
"monolog/monolog": "^3.0",
"psr/container": "^1.0|^2.0",
"symfony/translation": "~6.4.0",
"symfony/cache": "~6.4.0"
Expand Down
18 changes: 2 additions & 16 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/localzet-archive/FrameX-Public FrameX (v1-2)
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand All @@ -28,27 +28,18 @@

use Rector\CodeQuality\Rector\ClassMethod\LocallyCalledStaticMethodToNonStaticRector;
use Rector\CodeQuality\Rector\Empty_\SimplifyEmptyCheckOnEmptyArrayRector;
use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector;
use Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector;
use Rector\CodingStyle\Rector\Assign\SplitDoubleAssignRector;
use Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector;
use Rector\CodingStyle\Rector\Encapsed\WrapEncapsedVariableInCurlyBracesRector;
use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\Property\RemoveUnusedPrivatePropertyRector;
use Rector\DeadCode\Rector\PropertyProperty\RemoveNullPropertyInitializationRector;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Set\ValueObject\SetList;
use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;

return RectorConfig::configure()
->withPaths([
__DIR__ . '/src',
])
->withPhpSets(php84: true)
->withPhpSets()
->withSets([
LevelSetList::UP_TO_PHP_84,
SetList::PHP_84,

SetList::CODE_QUALITY,
SetList::CODING_STYLE,
SetList::DEAD_CODE,
Expand All @@ -64,12 +55,7 @@
->withSkip([
RemoveNullPropertyInitializationRector::class,
RemoveUnusedPrivatePropertyRector::class,
SimplifyIfElseToTernaryRector::class,
ExplicitBoolCompareRector::class,
SimplifyEmptyCheckOnEmptyArrayRector::class,
DisallowedEmptyRuleFixerRector::class,
LocallyCalledStaticMethodToNonStaticRector::class,
EncapsedStringsToSprintfRector::class,
WrapEncapsedVariableInCurlyBracesRector::class,
SplitDoubleAssignRector::class,
]);
2 changes: 1 addition & 1 deletion src/Annotation/DisableDefaultRoute.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/localzet-archive/FrameX-Public FrameX (v1-2)
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Annotation/Middleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/localzet-archive/FrameX-Public FrameX (v1-2)
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2025 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
Loading