Skip to content

[Workflow] Add support for executing custom workflow definition validators during the container compilation #54276

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 10, 2025
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 src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ CHANGELOG
* Allow configuring compound rate limiters
* Make `ValidatorCacheWarmer` use `kernel.build_dir` instead of `cache_dir`
* Make `SerializeCacheWarmer` use `kernel.build_dir` instead of `cache_dir`
* Support executing custom workflow validators during container compilation

7.2
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
use Symfony\Component\Validator\Validation;
use Symfony\Component\Webhook\Controller\WebhookController;
use Symfony\Component\WebLink\HttpHeaderSerializer;
use Symfony\Component\Workflow\Validator\DefinitionValidatorInterface;
use Symfony\Component\Workflow\WorkflowEvents;

/**
Expand Down Expand Up @@ -403,6 +404,7 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode): void
->useAttributeAsKey('name')
->prototype('array')
->fixXmlConfig('support')
->fixXmlConfig('definition_validator')
->fixXmlConfig('place')
->fixXmlConfig('transition')
->fixXmlConfig('event_to_dispatch', 'events_to_dispatch')
Expand Down Expand Up @@ -432,11 +434,28 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode): void
->prototype('scalar')
->cannotBeEmpty()
->validate()
->ifTrue(fn ($v) => !class_exists($v) && !interface_exists($v, false))
->ifTrue(static fn ($v) => !class_exists($v) && !interface_exists($v, false))
->thenInvalid('The supported class or interface "%s" does not exist.')
->end()
->end()
->end()
->arrayNode('definition_validators')
->prototype('scalar')
->cannotBeEmpty()
->validate()
->ifTrue(static fn ($v) => !class_exists($v))
->thenInvalid('The validation class %s does not exist.')
->end()
->validate()
->ifTrue(static fn ($v) => !is_a($v, DefinitionValidatorInterface::class, true))
->thenInvalid(\sprintf('The validation class %%s is not an instance of "%s".', DefinitionValidatorInterface::class))
->end()
->validate()
->ifTrue(static fn ($v) => 1 <= (new \ReflectionClass($v))->getConstructor()?->getNumberOfRequiredParameters())
->thenInvalid('The %s validation class constructor must not have any arguments.')
->end()
->end()
->end()
->scalarNode('support_strategy')
->cannotBeEmpty()
->end()
Expand All @@ -448,7 +467,7 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode): void
->variableNode('events_to_dispatch')
->defaultValue(null)
->validate()
->ifTrue(function ($v) {
->ifTrue(static function ($v) {
if (null === $v) {
return false;
}
Expand All @@ -475,14 +494,14 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode): void
->arrayNode('places')
->beforeNormalization()
->always()
->then(function ($places) {
->then(static function ($places) {
if (!\is_array($places)) {
throw new InvalidConfigurationException('The "places" option must be an array in workflow configuration.');
}

// It's an indexed array of shape ['place1', 'place2']
if (isset($places[0]) && \is_string($places[0])) {
return array_map(function (string $place) {
return array_map(static function (string $place) {
return ['name' => $place];
}, $places);
}
Expand Down Expand Up @@ -522,7 +541,7 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode): void
->arrayNode('transitions')
->beforeNormalization()
->always()
->then(function ($transitions) {
->then(static function ($transitions) {
if (!\is_array($transitions)) {
throw new InvalidConfigurationException('The "transitions" option must be an array in workflow configuration.');
}
Expand Down Expand Up @@ -589,20 +608,20 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode): void
->end()
->end()
->validate()
->ifTrue(function ($v) {
->ifTrue(static function ($v) {
return $v['supports'] && isset($v['support_strategy']);
})
->thenInvalid('"supports" and "support_strategy" cannot be used together.')
->end()
->validate()
->ifTrue(function ($v) {
->ifTrue(static function ($v) {
return !$v['supports'] && !isset($v['support_strategy']);
})
->thenInvalid('"supports" or "support_strategy" should be configured.')
->end()
->beforeNormalization()
->always()
->then(function ($values) {
->then(static function ($values) {
// Special case to deal with XML when the user wants an empty array
if (\array_key_exists('event_to_dispatch', $values) && null === $values['event_to_dispatch']) {
$values['events_to_dispatch'] = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1123,7 +1123,8 @@ private function registerWorkflowConfiguration(array $config, ContainerBuilder $
}
}
$metadataStoreDefinition->replaceArgument(2, $transitionsMetadataDefinition);
$container->setDefinition(\sprintf('%s.metadata_store', $workflowId), $metadataStoreDefinition);
$metadataStoreId = \sprintf('%s.metadata_store', $workflowId);
$container->setDefinition($metadataStoreId, $metadataStoreDefinition);

// Create places
$places = array_column($workflow['places'], 'name');
Expand All @@ -1134,7 +1135,8 @@ private function registerWorkflowConfiguration(array $config, ContainerBuilder $
$definitionDefinition->addArgument($places);
$definitionDefinition->addArgument($transitions);
$definitionDefinition->addArgument($initialMarking);
$definitionDefinition->addArgument(new Reference(\sprintf('%s.metadata_store', $workflowId)));
$definitionDefinition->addArgument(new Reference($metadataStoreId));
$definitionDefinitionId = \sprintf('%s.definition', $workflowId);

// Create MarkingStore
$markingStoreDefinition = null;
Expand All @@ -1148,14 +1150,26 @@ private function registerWorkflowConfiguration(array $config, ContainerBuilder $
$markingStoreDefinition = new Reference($workflow['marking_store']['service']);
}

// Validation
$workflow['definition_validators'][] = match ($workflow['type']) {
'state_machine' => Workflow\Validator\StateMachineValidator::class,
'workflow' => Workflow\Validator\WorkflowValidator::class,
default => throw new \LogicException(\sprintf('Invalid workflow type "%s".', $workflow['type'])),
};

// Create Workflow
$workflowDefinition = new ChildDefinition(\sprintf('%s.abstract', $type));
$workflowDefinition->replaceArgument(0, new Reference(\sprintf('%s.definition', $workflowId)));
$workflowDefinition->replaceArgument(0, new Reference($definitionDefinitionId));
$workflowDefinition->replaceArgument(1, $markingStoreDefinition);
$workflowDefinition->replaceArgument(3, $name);
$workflowDefinition->replaceArgument(4, $workflow['events_to_dispatch']);

$workflowDefinition->addTag('workflow', ['name' => $name, 'metadata' => $workflow['metadata']]);
$workflowDefinition->addTag('workflow', [
'name' => $name,
'metadata' => $workflow['metadata'],
'definition_validators' => $workflow['definition_validators'],
'definition_id' => $definitionDefinitionId,
]);
if ('workflow' === $type) {
$workflowDefinition->addTag('workflow.workflow', ['name' => $name]);
} elseif ('state_machine' === $type) {
Expand All @@ -1164,21 +1178,10 @@ private function registerWorkflowConfiguration(array $config, ContainerBuilder $

// Store to container
$container->setDefinition($workflowId, $workflowDefinition);
$container->setDefinition(\sprintf('%s.definition', $workflowId), $definitionDefinition);
$container->setDefinition($definitionDefinitionId, $definitionDefinition);
$container->registerAliasForArgument($workflowId, WorkflowInterface::class, $name.'.'.$type);
$container->registerAliasForArgument($workflowId, WorkflowInterface::class, $name);

// Validate Workflow
if ('state_machine' === $workflow['type']) {
$validator = new Workflow\Validator\StateMachineValidator();
} else {
$validator = new Workflow\Validator\WorkflowValidator();
}

$trs = array_map(fn (Reference $ref): Workflow\Transition => $container->get((string) $ref), $transitions);
$realDefinition = new Workflow\Definition($places, $trs, $initialMarking);
$validator->validate($realDefinition, $name);

// Add workflow to Registry
if ($workflow['supports']) {
foreach ($workflow['supports'] as $supportedClassName) {
Expand Down
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
use Symfony\Component\VarExporter\Internal\Registry;
use Symfony\Component\Workflow\DependencyInjection\WorkflowDebugPass;
use Symfony\Component\Workflow\DependencyInjection\WorkflowGuardListenerPass;
use Symfony\Component\Workflow\DependencyInjection\WorkflowValidatorPass;

// Help opcache.preload discover always-needed symbols
class_exists(ApcuAdapter::class);
Expand Down Expand Up @@ -173,6 +174,7 @@ public function build(ContainerBuilder $container): void
$container->addCompilerPass(new CachePoolPrunerPass(), PassConfig::TYPE_AFTER_REMOVING);
$this->addCompilerPassIfExists($container, FormPass::class);
$this->addCompilerPassIfExists($container, WorkflowGuardListenerPass::class);
$this->addCompilerPassIfExists($container, WorkflowValidatorPass::class);
$container->addCompilerPass(new ResettableServicePass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, -32);
$container->addCompilerPass(new RegisterLocaleAwareServicesPass());
$container->addCompilerPass(new TestServiceContainerWeakRefPass(), PassConfig::TYPE_BEFORE_REMOVING, -32);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,7 @@
<xsd:element name="initial-marking" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="marking-store" type="marking_store" minOccurs="0" maxOccurs="1" />
<xsd:element name="support" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="definition-validator" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="event-to-dispatch" type="event_to_dispatch" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="place" type="place" minOccurs="0" maxOccurs="unbounded" />
<xsd:element name="transition" type="transition" minOccurs="0" maxOccurs="unbounded" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\Workflow\Validator;

use Symfony\Component\Workflow\Definition;
use Symfony\Component\Workflow\Validator\DefinitionValidatorInterface;

class DefinitionValidator implements DefinitionValidatorInterface
{
public static bool $called = false;

public function validate(Definition $definition, string $name): void
{
self::$called = true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
'supports' => [
FrameworkExtensionTestCase::class,
],
'definition_validators' => [
Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\Workflow\Validator\DefinitionValidator::class,
],
'initial_marking' => ['draft'],
'metadata' => [
'title' => 'article workflow',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<framework:audit-trail enabled="true"/>
<framework:initial-marking>draft</framework:initial-marking>
<framework:support>Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\FrameworkExtensionTestCase</framework:support>
<framework:definition-validator>Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\Workflow\Validator\DefinitionValidator</framework:definition-validator>
<framework:place name="draft" />
<framework:place name="wait_for_journalist" />
<framework:place name="approved_by_journalist" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ framework:
type: workflow
supports:
- Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\FrameworkExtensionTestCase
definition_validators:
- Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\Workflow\Validator\DefinitionValidator
initial_marking: [draft]
metadata:
title: article workflow
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Psr\Log\LoggerAwareInterface;
use Symfony\Bundle\FrameworkBundle\DependencyInjection\FrameworkExtension;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Fixtures\Workflow\Validator\DefinitionValidator;
use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\Messenger\DummyMessage;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Bundle\FullStack;
Expand Down Expand Up @@ -287,7 +288,11 @@ public function testProfilerCollectSerializerDataEnabled()

public function testWorkflows()
{
$container = $this->createContainerFromFile('workflows');
DefinitionValidator::$called = false;

$container = $this->createContainerFromFile('workflows', compile: false);
$container->addCompilerPass(new \Symfony\Component\Workflow\DependencyInjection\WorkflowValidatorPass());
$container->compile();

$this->assertTrue($container->hasDefinition('workflow.article'), 'Workflow is registered as a service');
$this->assertSame('workflow.abstract', $container->getDefinition('workflow.article')->getParent());
Expand All @@ -310,6 +315,7 @@ public function testWorkflows()
], $tags['workflow'][0]['metadata'] ?? null);

$this->assertTrue($container->hasDefinition('workflow.article.definition'), 'Workflow definition is registered as a service');
$this->assertTrue(DefinitionValidator::$called, 'DefinitionValidator is called');

$workflowDefinition = $container->getDefinition('workflow.article.definition');

Expand Down Expand Up @@ -403,7 +409,9 @@ public function testWorkflowAreValidated()
{
$this->expectException(InvalidDefinitionException::class);
$this->expectExceptionMessage('A transition from a place/state must have an unique name. Multiple transitions named "go" from place/state "first" were found on StateMachine "my_workflow".');
$this->createContainerFromFile('workflow_not_valid');
$container = $this->createContainerFromFile('workflow_not_valid', compile: false);
$container->addCompilerPass(new \Symfony\Component\Workflow\DependencyInjection\WorkflowValidatorPass());
$container->compile();
}

public function testWorkflowCannotHaveBothSupportsAndSupportStrategy()
Expand Down
Loading
Loading