Skip to content

Creating custom rules

A custom rule lets your application express a decision that the built-in conditions do not cover. A rule implements a reusable check; each condition supplies the parameters for one use of that check on an edge. The engine asks the rule whether the choice is allowed, then continues or rejects that navigation attempt.

This tutorial implements a PHP rule through a plugin. It checks whether places requested in two categories fit within a capacity supplied by your application. The same rule can serve different graphs by reading the context keys named in each condition. You need an existing PHP integration with ExecKernel’s autoloader available; Condition evaluation and edge availability explains how conditions participate in navigation.

In this example, a person requests adult and child places. Your application supplies three context values:

Context key Meaning
adultPlaces Number of adult places requested.
childPlaces Number of child places requested.
availablePlaces Capacity against which this request is checked.

All three values must be nonnegative integers. The condition allows the choice when adultPlaces + childPlaces <= availablePlaces. It accepts an exact fit.

The rule will be called app_capacity. Its parameters name the three context keys, so another graph can use the same implementation with different field names. These parameters describe where to read values; the session context contains the actual numbers for the current attempt.

The rule checks the capacity your application provides. If these numbers represent bookable stock, your application still owns obtaining a current capacity and reserving places. A successful condition is a decision about these inputs; it does not reserve anything in another system.

RuleInterface requires getType() and evaluate(). The type identifies the implementation in conditions. Choose an application-specific name that does not collide with another plugin rule or a built-in type.

The evaluator receives four inputs: the condition’s params, the selected Edge, the candidate SessionState, and the evaluation time. Candidate state includes context updates supplied with the choice. This example only needs params and state->context; the other arguments remain part of the interface.

The following is the complete rule class. Its imports are shown because the result type is part of the contract: returning a bare boolean would not implement RuleInterface.

use ExecKernel\Domain\Engine\ConditionEvaluationResult;
use ExecKernel\Domain\Engine\Rules\RuleInterface;
use ExecKernel\Domain\Graph\Edge;
use ExecKernel\Domain\Session\SessionState;
use ExecKernel\Exception\InvalidRuleFormatException;
final class CapacityRule implements RuleInterface
{
public function getType(): string
{
return 'app_capacity';
}
public function evaluate(
array $params,
Edge $edge,
SessionState $state,
?DateTimeImmutable $now = null,
): ConditionEvaluationResult {
$values = [];
foreach (['first', 'second', 'capacity'] as $parameter) {
$key = $params[$parameter] ?? null;
if (!is_string($key) || trim($key) === '') {
throw new InvalidRuleFormatException(
'Capacity rule requires nonempty context keys.',
['rule' => $this->getType(), 'parameter' => $parameter],
);
}
$value = $state->context->get($key);
if (!is_int($value) || $value < 0) {
return ConditionEvaluationResult::blocked(
$this->getType(),
'capacity_input_invalid',
['field' => $key],
);
}
$values[$parameter] = $value;
}
$first = $values['first'];
$second = $values['second'];
$capacity = $values['capacity'];
// Equivalent to first + second > capacity, without integer overflow.
if ($first > $capacity || $second > $capacity - $first) {
return ConditionEvaluationResult::blocked(
$this->getType(),
'capacity_exceeded',
$values,
);
}
return ConditionEvaluationResult::allowed();
}
}

The first loop separates configuration from input data. A missing parameter means the graph has not told the rule which context key to read, so the implementation throws InvalidRuleFormatException. A missing, negative or noninteger context value produces the normal blocked result capacity_input_invalid, with the affected field. This is the input policy of this example; an HTML form’s string "3" must be validated and converted by your application before it becomes the integer 3.

Once the inputs are valid, the comparison checks their combined count. Subtracting the first count from the capacity avoids overflowing an integer when adding two very large counts. If the total fits, allowed() permits this condition. Otherwise, blocked() supplies the type, the application-defined reason capacity_exceeded, and diagnostic values.

Neither result moves the session. The engine uses it as part of the edge’s evaluation and completes the remaining navigation checks. Keep the implementation focused on that decision: reading the supplied state and returning a result makes repeated evaluation understandable.

A plugin contributes the rule class to a PluginRegistry. The plugin’s register() method performs the registration; its manifest declares the same class under provides.rules.

use ExecKernel\Domain\Engine\PluginInterface;
use ExecKernel\Domain\Engine\PluginRegistry;
use ExecKernel\Domain\Versioning\CompatibilityMode;
use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
final class CapacityPlugin implements PluginInterface
{
public function register(PluginRegistry $registry): void
{
$registry->addRule(CapacityRule::class);
}
public function boot(): void
{
}
}
$plugins = new PluginRegistry(
engineVersion: '0.2.0',
compatibilityMode: CompatibilityMode::STRICT,
);
$plugins->registerPlugin(new CapacityPlugin(), [
'name' => 'app-capacity',
'version' => '1.0.0',
'requires' => ['execkernel' => '0.2.0'],
'provides' => ['rules' => [CapacityRule::class]],
]);
$engine = (new ExecKernelFactory())->build(pluginRegistry: $plugins);

CapacityRule has no constructor dependencies, so the registry can instantiate it directly. A rule that needs an application service can supply a factory as the second argument to addRule(). The factory must return an instance of the declared class.

The two names serve different purposes: CapacityRule::class identifies PHP code in the manifest, while app_capacity identifies the rule in a graph condition. Register all plugins before constructing the engine. Building this engine consumes and seals the registry, and connects its rule implementations to the engine’s condition evaluator.

The manifest’s version belongs to this plugin; requires.execkernel is compared with the engine version your application passes to the registry. Plugin architecture and lifecycle explains that lifecycle and the registration checks.

The example graph has a decision at node 10 and a terminal at node 20. Edge 101, labelled Continue with these places, connects them. Create the condition with the type returned by getType():

use ExecKernel\Domain\Graph\Condition;
$condition = new Condition('app_capacity', [
'first' => 'adultPlaces',
'second' => 'childPlaces',
'capacity' => 'availablePlaces',
]);

When constructing the Graph, assign this condition to edge 101. The following extract shows the topology and that assignment; the complete example also supplies the bilingual labels, node titles and terminal content.

use ExecKernel\Domain\Graph\Edge;
use ExecKernel\Domain\Graph\Graph;
use ExecKernel\Domain\Graph\Node;
$graph = new Graph(
graphCode: 'capacity-request',
nodesById: [10 => new Node(10), 20 => new Node(20, isTerminal: true)],
rootNodeId: 10,
edgesFrom: [10 => [new Edge(101, 10, 20)]],
conditionsByEdge: [101 => [$condition]],
);

Registering a rule for evaluation does not teach every importer a new syntax. This tutorial deliberately uses Condition and Graph directly in PHP. In particular, the schema importer’s RuleFactory recognizes its defined rule vocabulary; installing this plugin does not add an app_capacity branch to that parser.

Using the fully presented graph from the download, your application can start a request for three adult and two child places against a capacity of six:

use ExecKernel\Domain\Session\Context;
use ExecKernel\Exception\ForbiddenEdgeException;
$start = $engine->start($graph, 'en', new Context([
'adultPlaces' => 3,
'childPlaces' => 2,
'availablePlaces' => 6,
]));
try {
$result = $engine->choose($graph, $start->state, 101, 'en');
$message = $result->payload['title'];
} catch (ForbiddenEdgeException $error) {
$message = match ($error->reason) {
'capacity_exceeded' => 'Reduce the number of requested places.',
'capacity_input_invalid' => 'Check the place counts and capacity.',
default => 'This choice is not available.',
};
}

The successful choice reaches node 20, whose title is Your request fits the capacity. On a rule rejection, choose() throws ForbiddenEdgeException; your application can translate the reason into useful feedback and retain the original state at node 10. The exception has ekCode: EK-SEC-NAV-002 and, for these blocked results, blockedEkCode: EK-RULE-003. Its details contain the values or field supplied by the rule.

A normal preview does not call an external rule’s evaluate(). Consequently, this graph’s option is pending, with enabled: true, before all four attempts below:

adultPlaces childPlaces availablePlaces Result of choosing edge 101
3 2 6 Accepted: five places fit; current node becomes 20.
4 2 6 Accepted: an exact fit; current node becomes 20.
5 2 6 Rejected: capacity_exceeded; original node remains 10.
"3" 2 6 Rejected: capacity_input_invalid, field adultPlaces.

pending lets your application offer an attempt; it is not an advance decision that the places fit. See Condition evaluation and edge availability for the full availability model.

The complete capacity-rule.php contains the class, plugin, graph and all four attempts. With that file next to your project’s vendor/ directory, php capacity-rule.php en prints the results above; php capacity-rule.php es uses the Spanish presentation and messages. The printed messages are chosen by the example application.

A plugin rule is useful when your PHP application owns a reusable implementation, its parameter contract and any dependencies. It runs as ordinary PHP in the application’s process. The sandbox driver used by custom_rule does not automatically wrap it.

The other route uses the built-in custom_rule type to select registered PHP source by a handler name. This is the mechanism introduced in Custom rule evaluation: its full boxes example accepts a quantity only when it fills complete boxes of six. Reusing that example, the essential registration is:

$engine = (new ExecKernelFactory())->build(
customRules: ['full_boxes' => $source],
sandboxDriver: $driver,
);

Here, $source is the trusted, installed PHP source string for full_boxes; $driver is your configured SandboxDriverInterface implementation. A graph condition selects rule: "custom_rule" and params.handler: "full_boxes". If the loader uses an allowlist, include the handler name in allowedCustomHandlers. Allowlisting a name, registering its source and configuring the driver are separate actions.

Choose a plugin rule when… Choose custom_rule when…
You want a PHP class implementing RuleInterface, with a type such as app_capacity. You want a named PHP source handler evaluated through the configured driver.
The implementation returns ConditionEvaluationResult, including your own rejection reason and details. The handler returns a boolean that the built-in wrapper translates into a condition result.
Your application manages the class and its dependencies. Your application manages the source registration, handler allowlist where used, and driver.

The Custom rules Showcase demonstrates the handler route and exposes its fixed source through Source code. Follow Custom rule evaluation for its data and failure behavior, and Rule sandboxing and isolation boundaries when choosing a driver. A driver’s name alone does not establish that it isolates untrusted code.