From a4496a59f480379908f35add7936b650fcc14a9f Mon Sep 17 00:00:00 2001 From: jerguslejko Date: Sat, 12 Oct 2019 16:02:50 +0100 Subject: [PATCH] change hook order --- src/Graph.php | 8 ++++---- tests/HooksTest.php | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/src/Graph.php b/src/Graph.php index 1f260aa..4ff3581 100644 --- a/src/Graph.php +++ b/src/Graph.php @@ -97,17 +97,17 @@ public function apply(Subject $subject, string $input): void $from = $this->getState($transition->getFrom()); $to = $this->getState($transition->getTo()); - $to->getHooks()->execute('entering', $subject); - $from->getHooks()->execute('leaving', $subject); $this->getHooks()->execute('applying', $subject, $from, $to, $transition); + $from->getHooks()->execute('leaving', $subject); $transition->getHooks()->execute('pre', $subject); + $to->getHooks()->execute('entering', $subject); $subject->setFiniteState($to->getKey()); + $to->getHooks()->execute('entered', $subject); $transition->getHooks()->execute('post', $subject); - $this->getHooks()->execute('applied', $subject, $from, $to, $transition); $from->getHooks()->execute('left', $subject); - $to->getHooks()->execute('entered', $subject); + $this->getHooks()->execute('applied', $subject, $from, $to, $transition); } /** diff --git a/tests/HooksTest.php b/tests/HooksTest.php index bb01000..61d78cb 100644 --- a/tests/HooksTest.php +++ b/tests/HooksTest.php @@ -399,6 +399,38 @@ public function entering_and_entered_hooks_are_executed_in_correct_order_when_in $this->assertEquals(['entering:[empty]', 'entered:new'], $states); } + /** @test */ + public function hooks_are_executed_in_fixed_order() + { + $events = ['applying', 'leaving', 'pre', 'entering', 'entered', 'post', 'left', 'applied']; + + $results = []; + + [$applying, $leaving, $pre, $entering, $entered, $post, $left, $applied] = array_map(function (string $event) use (&$results) { + return M::spy(function () use (&$results, $event) { + $results[] = $event; + }); + }, $events); + + $finite = Graph::make([ + State::initial('new') + ->leaving($leaving) + ->left($left), + + State::normal('foo') + ->entering($entering) + ->entered($entered), + ], [ + Transition::make('new', 'foo', 'a') + ->pre($pre) + ->post($post), + ])->applying($applying)->applied($applied); + + $finite->apply(new Subject('new'), 'a'); + + $this->assertEquals($events, $results); + } + /** @test */ public function objects_with_hooks_can_be_serialized() {