From f0adb6a120c5e48320d227855aec2a1d68e0e1fa Mon Sep 17 00:00:00 2001 From: Alexander Skvortsov <38059171+askvortsov1@users.noreply.github.com> Date: Mon, 13 Apr 2020 04:45:34 -0400 Subject: [PATCH] Add event extender (used for domain events) (#2097) --- framework/core/src/Extend/Event.php | 45 ++++++++++ .../tests/integration/extenders/EventTest.php | 84 +++++++++++++++++++ 2 files changed, 129 insertions(+) create mode 100644 framework/core/src/Extend/Event.php create mode 100644 framework/core/tests/integration/extenders/EventTest.php diff --git a/framework/core/src/Extend/Event.php b/framework/core/src/Extend/Event.php new file mode 100644 index 000000000..0f98ca6b9 --- /dev/null +++ b/framework/core/src/Extend/Event.php @@ -0,0 +1,45 @@ +listeners[] = [$event, $listener]; + + return $this; + } + + public function extend(Container $container, Extension $extension = null) + { + $events = $container->make(Dispatcher::class); + + foreach ($this->listeners as $listener) { + $events->listen($listener[0], $listener[1]); + } + } +} diff --git a/framework/core/tests/integration/extenders/EventTest.php b/framework/core/tests/integration/extenders/EventTest.php new file mode 100644 index 000000000..71466db16 --- /dev/null +++ b/framework/core/tests/integration/extenders/EventTest.php @@ -0,0 +1,84 @@ +app()->getContainer()->make(Dispatcher::class); + + $group = Group::build('test group', 'test groups', '#000000', 'fas fa-crown'); + $group->save(); + + $events->dispatch(new Created($group)); + + return $group; + } + + /** + * @test + */ + public function custom_listener_doesnt_work_by_default() + { + $group = $this->buildGroup(); + + $this->assertEquals($group->name_singular, 'test group'); + } + + /** + * @test + */ + public function custom_listener_works_with_closure() + { + $this->extend((new Extend\Event)->listen(Created::class, function (Created $event) { + $event->group->name_singular = 'modified group'; + })); + + $group = $this->buildGroup(); + + $this->assertEquals($group->name_singular, 'modified group'); + } + + /** + * @test + */ + public function custom_listener_works_with_class_with_handle_method_and_can_inject_stuff() + { + // Because it injects a translator, this also tests that stuff can be injected into this callback. + $this->extend((new Extend\Event)->listen(Created::class, CustomListener::class)); + + $group = $this->buildGroup(); + + $this->assertEquals($group->name_singular, 'core.group.admin'); + } +} + +class CustomListener +{ + protected $translator; + + public function __construct(Translator $translator) + { + $this->translator = $translator; + } + + public function handle(Created $event) + { + $event->group->name_singular = $this->translator->trans('core.group.admin'); + } +}