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
14 changes: 10 additions & 4 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ permissions:

jobs:
verify:
name: PHP ${{ matrix.php }}
name: PHP ${{ matrix.php }} / ${{ matrix.dependencies }} dependencies
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
php: ['8.1', '8.5']
dependencies: ['latest', 'lowest']
steps:
- name: Checkout
uses: actions/checkout@v7
Expand All @@ -31,11 +32,16 @@ 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 latest supported dependencies
if: matrix.dependencies == 'latest'
run: composer update --with-all-dependencies --no-interaction --no-progress --no-scripts

- name: Resolve lowest supported dependencies
if: matrix.dependencies == 'lowest'
run: composer update --with-all-dependencies --prefer-lowest --prefer-stable --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 Down
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@

Опорные файлы: `README.md`, `.github/CONTRIBUTING.md`.

`composer.json`: triangle/events; runtime "^8.1"; triangle/engine.
`composer.json`: `triangle/events`; PHP `^8.1`; `triangle/engine ^9.0`; `composer test` runs `tests/engine_compatibility.php`.

Именованных test/lint/build-скриптов в проверенных JSON-манифестах нет. Перед запуском выбери существующую команду из CI, конфигурации тестов или Makefile; не выдавай предполагаемую команду за проверенную.
CI resolves latest and lowest supported dependency versions on PHP 8.1 and 8.5. It validates Composer metadata, runs PHP syntax checks, and executes the declared test script.

Команды выше найдены в манифестах, а не проверены запуском. Перед выполнением прочитай их реализацию, нужные переменные и внешние зависимости. Не запускай нагрузочные, сетевые, deploy/migration-задачи или полный train как обычный smoke test.

Expand Down
8 changes: 7 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

---

## [Unreleased]
## [2.0.0] - Unreleased

### Breaking
- Require Triangle Engine 9.x for the plugin configuration hooks used by event bootstrap; Engine 8 is no longer supported.

### Changed
- Validate each converted event listener before registration.

### Planned
- Event broadcasting
Expand Down
43 changes: 43 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,46 @@
<img src="https://img.shields.io/github/license/Triangle-org/Events?label=%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F" alt="Лицензия">
</a>
</p>

# Triangle Events

Triangle Events registers application event listeners during Engine startup and provides an in-process dispatcher with exact-name and prefix listeners.

## Requirements

- PHP 8.1 or later
- Triangle Engine 9.x

Install the package with Composer:

```sh
composer require triangle/events:^2.0
```

## Register and dispatch events

```php
use support\Events;

Events::on('invoice.created', static function (array $invoice, string $event): void {
// Handle the created invoice.
});

Events::emit('invoice.created', ['id' => 42]);
```

Use a trailing `*` to register a prefix listener, for example `invoice.*`. Listeners receive the event payload followed by the event name. Dispatch is process-local; it does not provide durable queueing or cross-worker delivery.

Listeners can also be declared in `config/event.php`:

```php
return [
'invoice.created' => [
[App\Listeners\InvoiceCreated::class, 'handle'],
],
];
```

The Engine bootstrap loads application and plugin event configuration at startup. Engine 8 is not supported: this component uses the plugin configuration hooks introduced in Engine 9.

Русская версия: [README.ru.md](README.ru.md).
42 changes: 42 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Triangle Events

Triangle Events подключает обработчики событий при запуске Engine и предоставляет диспетчер внутри процесса с точными и префиксными именами событий.

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

- PHP 8.1 или новее
- Triangle Engine 9.x

Установите пакет через Composer:

```sh
composer require triangle/events:^2.0
```

## Регистрация и отправка событий

```php
use support\Events;

Events::on('invoice.created', static function (array $invoice, string $event): void {
// Обработать созданный счёт.
});

Events::emit('invoice.created', ['id' => 42]);
```

Для регистрации обработчика на группу событий используйте `*` в конце имени, например `invoice.*`. Обработчик получает данные события, а затем его имя. Диспетчер работает в памяти процесса: он не сохраняет сообщения и не передаёт их другим workers.

Обработчики также можно указать в `config/event.php`:

```php
return [
'invoice.created' => [
[App\Listeners\InvoiceCreated::class, 'handle'],
],
];
```

Engine загружает конфигурацию приложения и плагинов во время запуска. Engine 8 не поддерживается: компонент использует хуки конфигурации плагинов, добавленные в Engine 9.

English version: [README.md](README.md).
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@
},
"require": {
"php": "^8.1",
"triangle/engine": "^8.1"
"triangle/engine": "^9.0",
"psr/log": "^2.0 || ^3.0"
},
"scripts": {
"test": "php tests/engine_compatibility.php"
},
"suggest": {
},
Expand Down
4 changes: 2 additions & 2 deletions src/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public static function load(array $events): void
foreach ($callbacks as $callback) {
$callback = self::convertCallable($callback);

if (is_callable($callbacks)) {
if (is_callable($callback)) {
Events::on($event, $callback);
} else {
throw new RuntimeException("Событие: $event => " . var_export($callback, true) . " не вызываемо");
Expand All @@ -87,4 +87,4 @@ protected static function convertCallable(mixed $callbacks): mixed
}
return $callbacks;
}
}
}
44 changes: 44 additions & 0 deletions tests/engine_compatibility.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php declare(strict_types=1);

/**
* @package Triangle Events Component
* @link https://github.com/Triangle-org/Events
* @author Ivan Zorin <creator@localzet.com>
* @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
*/

require dirname(__DIR__) . '/vendor/autoload.php';

use support\Events;
use Triangle\Engine\BootstrapInterface;
use Triangle\Engine\Plugin;
use Triangle\Events\Bootstrap;

if (!is_a(Bootstrap::class, BootstrapInterface::class, true)) {
throw new RuntimeException('The event bootstrap must implement the Engine bootstrap contract.');
}

if (!method_exists(Plugin::class, 'app_reduce') || !method_exists(Plugin::class, 'plugin_reduce')) {
throw new RuntimeException('The event bootstrap requires Engine plugin reduction hooks.');
}

$event = 'triangle.events.bootstrap.compatibility';
$received = null;
$payload = ['source' => 'test'];

Bootstrap::load([
$event => [
static function (array $data) use (&$received): void {
$received = $data;
},
],
]);

Events::emit($event, $payload);

if ($received !== $payload) {
throw new RuntimeException('The configured event listener did not receive its payload.');
}

echo "TRIANGLE_EVENTS_ENGINE_COMPATIBILITY=ok\n";