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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ Latest

## Changes
* [#105](https://github.com/cleverage/process-bundle/issues/105) Conditional branches: the new `branches` key of a task configuration lists the tasks receiving its output by branch name, only when the task selects their branch with `ProcessState::setOutputBranch()` (in addition to its `outputs`); an unknown branch makes the execution fail, an unknown task or a task listed several times in the `outputs` and `branches` is rejected; `cleverage:process:help` shows the branch leading to each task. Update documentation, add tests.
* [#105](https://github.com/cleverage/process-bundle/issues/105) New `router` task: sends each input to the conditional branches of the task whose conditions it matches (conditions of `ConditionTrait` and an `expression`, by branch name), the first one (`mode: first`, default) or all of them (`mode: all`), else the `default` branch; without a default branch, an input matching no branch goes to the error outputs with a warning. The conditions and the default branch must match the `branches` of the task, checked at its initialization. Add the reference page and a recipe replacing a cascade of filters, add tests.
* [#428](https://github.com/cleverage/process-bundle/issues/428) Tests on PHPUnit 12.5 and 13 (PHPUnit 10 and 11 dropped), with the lowest dependencies on PHP 8.3 and 8.5.
* [#510](https://github.com/cleverage/process-bundle/issues/510) Support PHP 8.6: tests on PHP 8.6 (lowest dependencies, highest with Symfony 7.4 and 8.x), PHPStan and Rector on PHP 8.6, `symfony/polyfill-php86` is required so that the PHP 8.6 functions can be used on PHP 8.3 to 8.5.
* [#493](https://github.com/cleverage/process-bundle/issues/493) Documentation: the `constant()` function of the `evaluator` expressions is deprecated by Symfony 8.2 (a `ConstantFunctionProvider` must be registered), avoid it.
Expand Down
10 changes: 10 additions & 0 deletions config/services/task.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
use CleverAge\ProcessBundle\Task\Reporting\AdvancedStatCounterTask;
use CleverAge\ProcessBundle\Task\Reporting\LoggerTask;
use CleverAge\ProcessBundle\Task\Reporting\StatCounterTask;
use CleverAge\ProcessBundle\Task\RouterTask;
use CleverAge\ProcessBundle\Task\RowAggregatorTask;
use CleverAge\ProcessBundle\Task\Serialization\DenormalizerTask;
use CleverAge\ProcessBundle\Task\Serialization\DeserializerTask;
Expand Down Expand Up @@ -340,6 +341,15 @@
service('logger'),
]);

$services->set(RouterTask::class)
->tag('cleverage.task', ['code' => 'router'])
->share(false)
->args([
service('logger'),
service('property_accessor'),
service('cleverage_process.expression_language'),
]);

$services->set(RowAggregatorTask::class)
->tag('cleverage.task', ['code' => 'row_aggregator'])
->share(false)
Expand Down
4 changes: 4 additions & 0 deletions docs/04-advanced_workflow.md
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,10 @@ A task can send its output to some of its next tasks only: the tasks of its `bra
The selection is reset before each execution of the task. `cleverage:process:help` shows the branch leading to each
task (`[branch <task>.<branch>]`).

The [RouterTask](reference/tasks/router_task.md) selects the branches from conditions on the input (the first matching
branch or all of them, else a default branch), without code; a custom task calls `setOutputBranch()` itself, e.g. when
the branch depends on a service (see the [recipe](cookbooks/router.md)).

Unlike a [FilterTask](reference/tasks/filter_task.md) with `error_outputs`, the tasks of a branch are in the main
branch: the items of no branch are not mixed with the errors of the task. Some behaviours to know:
- a blocking task in a branch never selected is not proceeded: nothing comes out of it, without error; a flushable
Expand Down
111 changes: 111 additions & 0 deletions docs/cookbooks/router.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
Dispatching items with a router
===============================

This recipe dispatches the lines of a single file between several processings, according to their content: a typical
partner file mixing products, categories and comments.

```csv
type;code;label;total
product;P001;Chair;10
category;C01;Furniture;
product;P002;Table;2500
comment;;File of 2026-12-03;
promo;X1;Black Friday;
```

Before the [RouterTask](../reference/tasks/router_task.md), this was done with a cascade of
[FilterTask](../reference/tasks/filter_task.md), each rejected line going to the next filter through `error_outputs`:

```yaml
is_product:
task: filter
options: { match: { '[type]': product } }
outputs: [write_product]
error_outputs: [is_category] # "else", through the error channel
is_category:
task: filter
options: { match: { '[type]': category } }
outputs: [write_category] # the other lines are lost without trace
```

- The next filters and their tasks are an error branch (shown as such by `cleverage:process:help`).
- A failure of `is_product` with `error_strategy: skip` sends the line to `is_category`, as if it were not a product.
- Each new type adds a filter, and a line of no known type is silently dropped.

With a router, the dispatch is a single task, the lines of no known type are reported, and the errors stay errors:

```yaml
cleverage_process:
configurations:
app.import_catalog:
description: 'Import the catalog file of the partner'
tasks:
read:
task: csv_reader
options:
file_path: '%kernel.project_dir%/var/data/catalog.csv'
delimiter: ';'
outputs: [route]

route:
task: router
options:
mode: all
conditions:
product: { match: { '[type]': product } }
category: { match: { '[type]': category } }
comment: { match: { '[type]': comment } }
big: { expression: 'data["type"] == "product" and data["total"] > 1000' }
default: unknown # a line of no known type (e.g. promo)
outputs: [count] # every line
branches:
product: [write_product]
category: [write_category]
comment: [] # ignored
big: [log_big]
unknown: [log_unknown]

count:
task: stat_counter

write_product:
task: csv_writer
options:
file_path: '%kernel.project_dir%/var/exports/products.csv'

write_category:
task: csv_writer
options:
file_path: '%kernel.project_dir%/var/exports/categories.csv'

log_big:
task: logger
options:
level: notice
message: 'Big product'

log_unknown:
task: logger
options:
level: warning
message: 'Unknown line type'
```

How it works:
- [CsvReaderTask](../reference/tasks/csv_reader_task.md) is iterable: each line goes through the router before the
next one is read.
- The [RouterTask](../reference/tasks/router_task.md) sends every line to its `outputs` (the
[StatCounterTask](../reference/tasks/stat_counter_task.md)), and to the tasks of the branches it matches. With
`mode: all`, the line `P002` goes to `write_product` and `log_big`; with the default `mode: first`, only the first
matching branch (in the order of `conditions`) would get it.
- The `comment` branch has no task: the comments are dropped on purpose, without warning.
- The line `promo` matches no branch: it goes to the `default` branch, `log_unknown`. Without a `default` branch, it
would go to the `error_outputs` of the router, with a warning, mixed with the errors of the router (e.g. a missing
key in an expression, with `error_strategy: skip`): a `default` branch keeps them apart.
- `cleverage:process:help app.import_catalog` shows the branch leading to each task (`write_product [branch
route.product]`), in the main branch.

Keep the [FilterTask](../reference/tasks/filter_task.md) to drop the items that do not match (e.g. the lines without
`sku`): a router is meant to dispatch them. The branches of a router cannot be joined back with an
[InputAggregatorTask](../reference/tasks/input_aggregator_task.md), see
[conditional branches](../04-advanced_workflow.md#conditional-branches).
2 changes: 2 additions & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- [ETL report aggregation](cookbooks/etl_aggregate_reports.md)
- [Performances monitoring](cookbooks/performances_monitoring.md)
- [Memory usage analysis](cookbooks/memory_usage_graph.md)
- [Dispatching items with a router](cookbooks/router.md)
- Reference
- [Process definition](reference/01-process_definition.md)
- [Task definition](reference/02-task_definition.md)
Expand Down Expand Up @@ -74,6 +75,7 @@
- [ColumnAggregatorTask](reference/tasks/column_aggregator_task.md)
- [RowAggregatorTask](reference/tasks/row_aggregator_task.md)
- [FilterTask](reference/tasks/filter_task.md)
- [RouterTask](reference/tasks/router_task.md)
- [GroupByAggregateIterableTask](reference/tasks/group_by_aggregate_iterable_task.md)
- [SimpleBatchTask](reference/tasks/simple_batch_task.md)
- [IterableBatchTask](reference/tasks/iterable_batch_task.md)
Expand Down
4 changes: 4 additions & 0 deletions docs/reference/tasks/filter_task.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ FilterTask
Passes the input to the output only if it matches all the configured conditions. Otherwise, the input is sent to the
error output and the task is skipped.

Use it to drop the items that do not match (and optionally report them through `error_outputs`). To dispatch the items
between several processings, use the [RouterTask](router_task.md) instead of a cascade of filters linked by their
`error_outputs` (see the [recipe](../../cookbooks/router.md)).

Task reference
--------------

Expand Down
111 changes: 111 additions & 0 deletions docs/reference/tasks/router_task.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
RouterTask
==========

Sends each input to the [conditional branches](../../04-advanced_workflow.md#conditional-branches) of the task whose
conditions it matches: the first matching branch, or all of them, else a default branch. Use it to dispatch the items
between several processings (e.g. the lines of a file by type, the responses of an API by status); to drop the items
that do not match, use the [FilterTask](filter_task.md).

The conditions are given by branch name in the `conditions` option, the tasks of each branch in the `branches` key of
the task configuration (see [task definition](../02-task_definition.md)). Each branch of the task must have conditions
or be the `default` branch, and each branch of the options must be a branch of the task: otherwise the process fails
at the initialization of the task, before any input.

Task reference
--------------

* **Service**: `CleverAge\ProcessBundle\Task\RouterTask`
* **Code**: `router` (`task: router`)

Accepted inputs
---------------

`any`: the conditions of [ConditionTrait](../traits/condition_trait.md) read the values of an `array` or an `object`
with the Symfony PropertyAccessor (a non-readable property is `null`, use the empty path `''` for a scalar input); an
`expression` gets the input as the `data` variable.

Possible outputs
----------------

`any`: the input, unchanged, sent to the `outputs` of the task and to the tasks of the selected branches.

Error output: the input, unchanged, when it matches no branch and there is no `default` branch (logged as a warning on
the `cleverage_process_task` channel). An error while checking a condition (e.g. an expression calling a method of an
array, a missing array key) makes the task fail: its `error_strategy` applies, the input never goes to the default
branch. Both go to the same error outputs: use a `default` branch to keep the inputs of no branch apart from the errors.

Options
-------

| Code | Type | Required | Default | Description |
|--------------|-------------------------|:--------:|---------|--------------------------------------------------------------------------------------|
| `conditions` | `array` | **X** | | Branch name => conditions of the branch (see below); all of them must hold |
| `mode` | `string` | | `first` | `first`: the first matching branch, in the order of `conditions`; `all`: all of them |
| `default` | `string`, `int`, `null` | | `null` | Branch of the inputs matching no branch; `null`: they go to the error outputs |

The conditions of a branch are the options of [ConditionTrait](../traits/condition_trait.md) (`match`, `not_match`,
`empty`, `not_empty`, `match_regexp`, `not_match_regexp`) and `expression`, a Symfony
[ExpressionLanguage](https://symfony.com/doc/current/components/expression_language.html) expression evaluated with the
input as `data` (the bundle's `cleverage_process.expression_language` service, with its `preg_match` function, as in
the [RulesTransformer](../transformers/rules_transformer.md)); its result is cast to `bool`. A branch without conditions
(`~`) matches every input; another value than a mapping or `~` is rejected. An expression gives the alternatives
(`or`) the other conditions cannot express. A missing array key in an expression is an error: give a default value
when the key may be missing (`(data["total"] ?? 0) > 1000`).

Do not put a `{{ key }}` contextual value in an `expression`: it is replaced before the expression is parsed, so a value
given by the context (command line, scheduler, UI form) would become expression code and change the routing. Read the
values in the input (`data`) instead.

Examples
--------

* Dispatch the lines of a catalog file by type, ignore the comments, report the unknown types

```yaml
# Task configuration level
route:
task: router
options:
conditions:
product: { match: { '[type]': product } }
category: { match: { '[type]': category } }
comment: { match: { '[type]': comment } }
outputs: [count] # every line
branches:
product: [write_product]
category: [write_category]
comment: [] # ignored
error_outputs: [report] # an unknown type, with a warning
```

* Route the responses of an API by status code, with a default branch; flag the big orders as well (mode `all`)

```yaml
# Task configuration level
route_status:
task: router
options:
conditions:
200: { match: { '[status]': 200 } }
404: { match: { '[status]': 404 } }
default: failed
branches:
200: [update_stock]
404: [disable_product]
failed: [alert]

route_order:
task: router
options:
mode: all
conditions:
erp: ~ # every order
big_order: { expression: 'data["total"] > 1000 or data["vip"]' }
branches:
erp: [export_erp]
big_order: [notify_sales]
```

See the [conditional branches](../../04-advanced_workflow.md#conditional-branches) for the behaviour of the branches
(blocking tasks, end point, no join with an [InputAggregatorTask](input_aggregator_task.md)), and the
[recipe](../../cookbooks/router.md) replacing a cascade of filters.
1 change: 1 addition & 0 deletions docs/reference/traits/condition_trait.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ array_filter:
## Implementors

* [FilterTask](../tasks/filter_task.md): condition options at the root of the task options
* [RouterTask](../tasks/router_task.md): condition options of each branch, in its `conditions` option
* [ColumnAggregatorTask](../tasks/column_aggregator_task.md): `condition` option, checked against
`{input_column_value: <column value>, input: <input>}` (so use paths like `[input_column_value]` or `[input][key]`)
* [ArrayFilterTransformer](../transformers/array_filter_transformer.md): `condition` option, checked against each item
Expand Down
14 changes: 7 additions & 7 deletions src/Configuration/TaskConfiguration.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,17 @@ final class TaskConfiguration
/**
* The next tasks of each branch, indexed by branch name.
*
* @var array<string, list<TaskConfiguration>>
* @var array<int|string, list<TaskConfiguration>>
*/
protected array $branchTasksConfigurations = [];

protected bool $inErrorBranch = false;

/**
* @param array<string, mixed> $options
* @param list<string> $outputs
* @param list<string> $errorOutputs
* @param array<string, list<string>> $branches tasks receiving the output when the task selects their branch
* @param array<string, mixed> $options
* @param list<string> $outputs
* @param list<string> $errorOutputs
* @param array<int|string, list<string>> $branches tasks receiving the output when the task selects their branch
*/
public function __construct(
protected string $code,
Expand Down Expand Up @@ -140,7 +140,7 @@ public function getErrorOutputs(): array
/**
* The codes of the tasks of each branch, indexed by branch name.
*
* @return array<string, list<string>>
* @return array<int|string, list<string>>
*/
public function getBranches(): array
{
Expand Down Expand Up @@ -173,7 +173,7 @@ public function addNextTaskConfiguration(self $nextTaskConfiguration): void
/**
* The next tasks of each branch, indexed by branch name: they are also in getNextTasksConfigurations().
*
* @return array<string, list<TaskConfiguration>>
* @return array<int|string, list<TaskConfiguration>>
*/
public function getBranchTasksConfigurations(): array
{
Expand Down
Loading