From a3797b976a5ab6e81924b98e08c8a7840cddb78e Mon Sep 17 00:00:00 2001 From: Jan Jakes Date: Wed, 14 Sep 2022 15:12:25 +0200 Subject: [PATCH] Add triggers under root rule for workflow validation [MAILPOET-4629] --- .../WorkflowRules/TriggersUnderRootRule.php | 40 +++++++++++++++++++ .../TriggersUnderRootRuleTest.php | 34 ++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 mailpoet/lib/Automation/Engine/Validation/WorkflowRules/TriggersUnderRootRule.php create mode 100644 mailpoet/tests/unit/Automation/Engine/Validation/WorkflowRules/TriggersUnderRootRuleTest.php diff --git a/mailpoet/lib/Automation/Engine/Validation/WorkflowRules/TriggersUnderRootRule.php b/mailpoet/lib/Automation/Engine/Validation/WorkflowRules/TriggersUnderRootRule.php new file mode 100644 index 0000000000..711766d710 --- /dev/null +++ b/mailpoet/lib/Automation/Engine/Validation/WorkflowRules/TriggersUnderRootRule.php @@ -0,0 +1,40 @@ + $triggersMap */ + private $triggersMap = []; + + public function initialize(Workflow $workflow): void { + $this->triggersMap = []; + foreach ($workflow->getSteps() as $step) { + if ($step->getType() === 'trigger') { + $this->triggersMap[$step->getId()] = $step; + } + } + } + + public function visitNode(Workflow $workflow, WorkflowNode $node): void { + $step = $node->getStep(); + if ($step->getType() === Step::TYPE_ROOT) { + return; + } + + foreach ($step->getNextSteps() as $nextStep) { + $nextStepId = $nextStep->getId(); + if (isset($this->triggersMap[$nextStepId])) { + throw Exceptions::workflowStructureNotValid(__('Trigger must be a direct descendant of workflow root', 'mailpoet')); + } + } + } + + public function complete(Workflow $workflow): void { + } +} diff --git a/mailpoet/tests/unit/Automation/Engine/Validation/WorkflowRules/TriggersUnderRootRuleTest.php b/mailpoet/tests/unit/Automation/Engine/Validation/WorkflowRules/TriggersUnderRootRuleTest.php new file mode 100644 index 0000000000..467255d018 --- /dev/null +++ b/mailpoet/tests/unit/Automation/Engine/Validation/WorkflowRules/TriggersUnderRootRuleTest.php @@ -0,0 +1,34 @@ +make(Workflow::class, ['getSteps' => [ + 'root' => $this->createStep('root', Step::TYPE_ROOT, ['t', 'a']), + 'a' => $this->createStep('a', Step::TYPE_ACTION, ['t']), + 't' => $this->createStep('t', Step::TYPE_TRIGGER, []), + ]]); + + $this->expectException(UnexpectedValueException::class); + $this->expectExceptionMessage('Invalid workflow structure: Trigger must be a direct descendant of workflow root'); + (new WorkflowWalker())->walk($workflow, [new TriggersUnderRootRule()]); + } + + public function testItPassesWithTriggersUnderRoot(): void { + $workflow = $this->make(Workflow::class, ['getSteps' => [ + 'root' => $this->createStep('root', Step::TYPE_ROOT, ['t']), + 't' => $this->createStep('t', Step::TYPE_TRIGGER, []), + ]]); + + (new WorkflowWalker())->walk($workflow, [new TriggersUnderRootRule()]); + // no exception thrown + } +}