Skip to content

Custom validators and loaders

A custom loader connects ExecKernel to a source of graph definitions that your application already uses. A custom validator checks a requirement that those definitions must satisfy before your application makes them available. Both work with graphs before navigation, but they solve different problems: obtaining a definition and deciding whether to accept it.

This page contains two independent recipes. The first loads a support-request graph through an application repository. The second requires a Spanish title for every node of a graph used by a bilingual application. Each recipe has its own complete download and assumes ExecKernel’s Composer autoloader is already available.

A definition is data: arrays of nodes, edges, metadata and related records. A Graph is the constructed object the engine uses. A repository returns the definition; a loader validates and constructs the graph; a validator accepts the definition or raises an error.

Contract Input and result Where it connects
GraphRepositoryInterface fetch(string|int $graphCode): array returns one complete normalized definition. Your loader receives the repository as a dependency.
GraphLoaderInterface load(string|int $graphCode): Graph returns an executable graph. PluginRegistry::addLoader(), then PluginLoaderFactory, or direct application construction.
GraphValidatorInterface validate(array $graphDefinition): void. PluginRegistry::addValidator(); the loader passes registered validators to the default validation pipeline.
GraphValidationRuleInterface validate(RawGraphData $data): void. A rule in GraphValidationPipeline; this is not the interface accepted by addValidator().

RawGraphData groups the normalized definition and exposes methods such as nodes(), metadata() and toArray(). The built-in PluginGraphValidatorRule adapts a plugin validator to that pipeline contract by calling its validate() method with $data->toArray(). You do not need to implement that conversion yourself when using the loader’s plugin integration.

The Graph loaders and repositories guide explains the built-in sources. Use the first recipe when your own source needs an adapter; use the second when the source already works and the additional requirement concerns its contents.

Recipe: load from your application’s repository

Section titled “Recipe: load from your application’s repository”

Suppose your application stores a definition named support-request. It has a review node 10, a terminal 20, and edge 101 between them. The repository must return one complete snapshot in the normalized array format understood by ArrayGraphLoader, including graph_code, root_node_id, nodes and edges.

Your repository implements ExecKernel\Infrastructure\Repository\GraphRepositoryInterface. Its fetch('support-request') operation reads that definition from your storage; it does not start a session. The complete repository-loader.php example supplies an ApplicationGraphRepository backed by an in-memory map so that the integration can run without a database. Replace that class’s lookup with your own storage read while preserving the complete-definition contract.

Delegate graph construction to the existing loader

Section titled “Delegate graph construction to the existing loader”

The custom loader is small because it only adds the source lookup. It passes the returned data to ArrayGraphLoader, which performs the normal structural and consistency checks and constructs the Graph.

use ExecKernel\Domain\Engine\PluginRegistry;
use ExecKernel\Domain\Graph\Graph;
use ExecKernel\Domain\Graph\GraphLoaderInterface;
use ExecKernel\Infrastructure\Loader\ArrayGraphLoader;
use ExecKernel\Infrastructure\Repository\GraphRepositoryInterface;
final class RepositoryGraphLoader implements GraphLoaderInterface
{
public function __construct(
private readonly GraphRepositoryInterface $repository,
private readonly PluginRegistry $plugins,
) {
}
public function load(string|int $graphCode): Graph
{
$definition = $this->repository->fetch($graphCode);
return (new ArrayGraphLoader(
$definition,
pluginRegistry: $this->plugins,
engineVersion: '0.2.0',
))->load($graphCode);
}
}

Passing $graphCode to the inner load() preserves the identity check. A repository that accidentally returns a different definition must not make your application execute it under the requested name. This example repository requires a nonempty string code and rejects integer requests; the wider interface also permits adapters that support integer identities.

The same registry is passed into ArrayGraphLoader so its validators, rule types and terminal output types can participate in loading. If your application later adds a presentation validator, this loader can use it without rewriting its source lookup.

The loader needs both the repository and the registry in its constructor. Supply a factory that creates that declared loader class with those dependencies:

use ExecKernel\Domain\Engine\PluginInterface;
final class RepositoryLoaderPlugin implements PluginInterface
{
public function __construct(
private readonly GraphRepositoryInterface $repository,
) {
}
public function register(PluginRegistry $registry): void
{
$repository = $this->repository;
$registry->addLoader(
RepositoryGraphLoader::class,
static fn (): RepositoryGraphLoader =>
new RepositoryGraphLoader($repository, $registry),
);
}
public function boot(): void
{
}
}

The factory creates the loader when requested; registering it does not fetch a graph. In the following application configuration, $repository is your initialized GraphRepositoryInterface object:

use ExecKernel\Domain\Versioning\CompatibilityMode;
use ExecKernel\Infrastructure\Loader\PluginLoaderFactory;
$plugins = new PluginRegistry(
engineVersion: '0.2.0',
compatibilityMode: CompatibilityMode::STRICT,
);
$plugins->registerPlugin(new RepositoryLoaderPlugin($repository), [
'name' => 'app-repository-loader',
'version' => '1.0.0',
'requires' => ['execkernel' => '0.2.0'],
'provides' => ['loaders' => [RepositoryGraphLoader::class]],
]);
$factory = new PluginLoaderFactory($plugins, [
'application' => RepositoryGraphLoader::class,
]);
$loader = $factory->create('application');
$graph = $loader->load('support-request');

The alias application chooses a registered loader; support-request chooses a graph within its repository. They are separate identifiers. You could also call create(RepositoryGraphLoader::class) without an alias. An alias cannot make an unregistered class available.

Register all plugins before create(): instantiating the loader seals the registry. Here, strict compatibility on PluginRegistry checks the plugin’s declared engine requirement. The definition in the download separately uses strict_validation: true for structural validation.

Once loading succeeds, your application can start the graph normally:

use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
$engine = (new ExecKernelFactory())->build(pluginRegistry: $plugins);
$result = $engine->start($graph, 'en');
$title = $result->payload['title'];
$option = $result->payload['edges'][0]['labels'][0]['text'];

The complete example returns these values:

{
"graph_code": "support-request",
"root_node_id": 10,
"nodes": 2,
"title": "Review your support request",
"option": "Continue"
}

Your application can present the title and use the option text on a button while retaining edge ID 101 for the choice. The repository source has not changed how navigation works.

Handle a failed repository read as a source problem. In this example, a missing code raises an application RuntimeException; an identity mismatch or malformed returned definition is rejected by the inner loader. Neither case returns a graph. The loader does not supply a replacement definition or restore session progress.

A graph can be structurally valid while lacking a translation your application requires. For a bilingual application, suppose every node must have its own Spanish title before the definition is published. The engine’s default-language checks do not express that additional requirement: a graph whose default language is English can have all its English titles and still lack a Spanish record.

This recipe uses a separate graph, account-help. Node 1 offers an account guide and edge 11 leads to terminal 2. Both nodes have English metadata, but only node 1 initially has Spanish metadata.

A metadata record associates a title and optional presentation fields with a node and language. This is the presentation data described in Payloads, metadata and presentation. The validator below checks the presence of the required record; your application still decides how to render its title.

Implement GraphValidatorInterface because this validator will be registered by a plugin. It indexes nodes that have a nonempty title in the required language, then reports the first node missing one.

use ExecKernel\Domain\Engine\GraphValidatorInterface;
use ExecKernel\Exception\GraphValidationException;
final class RequiredTitleValidator implements GraphValidatorInterface
{
public function __construct(private readonly string $language)
{
}
public function validate(array $graphDefinition): void
{
$translated = [];
foreach ($graphDefinition['metadata'] ?? [] as $entry) {
if (($entry['lang'] ?? null) === $this->language
&& is_int($entry['node_id'] ?? null)
&& is_string($entry['title'] ?? null)
&& trim($entry['title']) !== '') {
$translated[$entry['node_id']] = true;
}
}
foreach ($graphDefinition['nodes'] as $node) {
if (!isset($translated[$node['id']])) {
throw new GraphValidationException(
sprintf('Node %d requires a title in %s.', $node['id'], $this->language),
[
'graph_code' => $graphDefinition['graph_code'],
'node_id' => $node['id'],
'lang' => $this->language,
'field' => 'metadata',
'requirement' => 'translated_title',
],
);
}
}
}
}

The method returns normally when the requirement is satisfied. It throws GraphValidationException when the definition should be rejected. The context identifies the graph, node, language and missing collection, so an editor can take the person directly to the record that needs attention.

This class checks a definition, not the current person’s session values. A condition that decides whether someone may choose an edge belongs to a runtime rule such as those in Creating custom rules.

The plugin fixes the required language to es through a factory:

use ExecKernel\Domain\Engine\PluginInterface;
use ExecKernel\Domain\Engine\PluginRegistry;
use ExecKernel\Domain\Versioning\CompatibilityMode;
use ExecKernel\Infrastructure\Loader\ArrayGraphLoader;
final class PresentationPlugin implements PluginInterface
{
public function register(PluginRegistry $registry): void
{
$registry->addValidator(
RequiredTitleValidator::class,
static fn (): RequiredTitleValidator => new RequiredTitleValidator('es'),
);
}
public function boot(): void
{
}
}
$plugins = new PluginRegistry(
engineVersion: '0.2.0',
compatibilityMode: CompatibilityMode::STRICT,
);
$plugins->registerPlugin(new PresentationPlugin(), [
'name' => 'app-presentation',
'version' => '1.0.0',
'requires' => ['execkernel' => '0.2.0'],
'provides' => ['validators' => [RequiredTitleValidator::class]],
]);

Now pass this registry to the loader. Here, $definition is the complete account-help array from presentation-validator.php, with strict_validation: true.

$loader = new ArrayGraphLoader(
$definition,
pluginRegistry: $plugins,
engineVersion: '0.2.0',
);
$graph = $loader->load('account-help');

During load(), the loader normalizes the definition, obtains the plugin validators and runs its validation pipeline. The default pipeline runs the built-in checks before the plugin checks. Registering the class alone would not add it to an unrelated loader: the pluginRegistry argument makes this connection.

Return an actionable diagnostic, then repair the definition

Section titled “Return an actionable diagnostic, then repair the definition”

The first load fails because node 2 lacks a Spanish metadata record. ArrayGraphLoader wraps the validator’s error as InvalidGraphStructureException. Its relevant diagnostic is:

{
"ek_code": "EK-SEC-LOD-001",
"message": "Node 2 requires a title in es.",
"context": {
"graph_code": "account-help",
"node_id": 2,
"lang": "es",
"field": "metadata",
"requirement": "translated_title",
"validation_ek_code": "EK-VALID-001"
}
}

EK-SEC-LOD-001 identifies the rejected loading operation. validation_ek_code preserves the validator’s underlying code. The application-specific requirement, node and language tell your editor what to repair. Your application can display Add a Spanish title for node 2 before publishing this graph, while retaining the original diagnostic for troubleshooting.

Add the missing record:

$definition['metadata'][] = [
'node_id' => 2,
'lang' => 'es',
'title' => 'Guía de tu cuenta preparada',
];

Construct a new ArrayGraphLoader with the corrected array and the same registry, then load again. A loader retains the array passed to its constructor; changing the separate $definition variable does not update an existing loader.

The download performs that correction, loads the graph successfully and chooses edge 11. In Spanish, the terminal now presents Guía de tu cuenta preparada. The successful load has zero warnings, obtainable through $loader->validationResult()?->warnings(). Other graphs can produce warnings even when loading succeeds; Graph validation and diagnostics explains how to use them.

The validator’s exception rejects this definition. Its void plugin contract has no warning return channel; returning a diagnostic array would not report a warning through the adapter. A pipeline rule that produces warnings uses the separate GraphValidationWarningRuleInterface contract.

If your integration works directly with RawGraphData, use GraphValidationRuleInterface for a rule in that pipeline. To reuse the plugin validator there, the existing adapter is sufficient:

use ExecKernel\Infrastructure\Validation\Rules\PluginGraphValidatorRule;
// $rawData is the normalized RawGraphData used by your validation pipeline.
$rule = new PluginGraphValidatorRule(new RequiredTitleValidator('es'));
$rule->validate($rawData);

That call performs only the added title check; keep the other structural checks in your pipeline. GraphValidationPipeline::default(validators: ...) creates these adapters for the supplied GraphValidatorInterface instances, which is the path ArrayGraphLoader already uses.

An existing class that implements only GraphValidationRuleInterface cannot be passed to addValidator(). Either keep it in the pipeline it was written for or provide a GraphValidatorInterface adapter with the array input that plugin registration requires. The similarly named interfaces describe different boundaries.

repository-loader.php includes the repository, normalized definition, loader, plugin and application result. presentation-validator.php includes the validator, its plugin, the incomplete definition, the diagnostic and the corrected load.

Each download is independent. With the chosen file next to your project’s vendor/ directory, run php repository-loader.php en or php presentation-validator.php en; use es for Spanish application text. The examples demonstrate integration in an existing project and do not require changes to ExecKernel’s built-in loaders.

For registration lifecycle and dependencies, see Plugin architecture and lifecycle. The complete interface catalogue belongs to PHP interfaces and Plugin extension contracts.