From 47c68e12ea9feda162875cb61009f817ea35237c Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Thu, 3 Aug 2017 20:22:22 +0200 Subject: [PATCH] [Workflow] do not emit not needed guard events --- .../Component/Workflow/Tests/WorkflowTest.php | 25 +++++++++++++++++++ src/Symfony/Component/Workflow/Workflow.php | 13 ++++++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/src/Symfony/Component/Workflow/Tests/WorkflowTest.php b/src/Symfony/Component/Workflow/Tests/WorkflowTest.php index 3ca61914aad1..45dcbc73ccb6 100644 --- a/src/Symfony/Component/Workflow/Tests/WorkflowTest.php +++ b/src/Symfony/Component/Workflow/Tests/WorkflowTest.php @@ -137,6 +137,31 @@ public function testCanWithGuard() $this->assertFalse($workflow->can($subject, 't1')); } + public function testCanDoesNotTriggerGuardEventsForNotEnabledTransitions() + { + $definition = $this->createComplexWorkflowDefinition(); + $subject = new \stdClass(); + $subject->marking = null; + + $dispatchedEvents = array(); + $eventDispatcher = new EventDispatcher(); + + $workflow = new Workflow($definition, new MultipleStateMarkingStore(), $eventDispatcher, 'workflow_name'); + $workflow->apply($subject, 't1'); + $workflow->apply($subject, 't2'); + + $eventDispatcher->addListener('workflow.workflow_name.guard.t3', function () use (&$dispatchedEvents) { + $dispatchedEvents[] = 'workflow_name.guard.t3'; + }); + $eventDispatcher->addListener('workflow.workflow_name.guard.t4', function () use (&$dispatchedEvents) { + $dispatchedEvents[] = 'workflow_name.guard.t4'; + }); + + $workflow->can($subject, 't3'); + + $this->assertSame(array('workflow_name.guard.t3'), $dispatchedEvents); + } + /** * @expectedException \Symfony\Component\Workflow\Exception\LogicException * @expectedExceptionMessage Unable to apply transition "t2" for workflow "unnamed". diff --git a/src/Symfony/Component/Workflow/Workflow.php b/src/Symfony/Component/Workflow/Workflow.php index 617c05b381e0..6f22fb7dc384 100644 --- a/src/Symfony/Component/Workflow/Workflow.php +++ b/src/Symfony/Component/Workflow/Workflow.php @@ -92,10 +92,19 @@ public function getMarking($subject) */ public function can($subject, $transitionName) { - $transitions = $this->getEnabledTransitions($subject); + $transitions = $this->definition->getTransitions(); + $marking = $this->getMarking($subject); foreach ($transitions as $transition) { - if ($transitionName === $transition->getName()) { + foreach ($transition->getFroms() as $place) { + if (!$marking->has($place)) { + // do not emit guard events for transitions where the marking does not contain + // all "from places" (thus the transition couldn't be applied anyway) + continue 2; + } + } + + if ($transitionName === $transition->getName() && $this->doCan($subject, $marking, $transition)) { return true; } }