From d006748eb3375eb5fdb5b04be7eac19c988a3db0 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Tue, 16 Aug 2022 14:53:31 -0700 Subject: [PATCH] HookStyleServiceListenerTest - Add test for running `hook_foo(&$alterable)` --- .../Event/HookStyleServiceListenerTest.php | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 tests/phpunit/Civi/Core/Event/HookStyleServiceListenerTest.php diff --git a/tests/phpunit/Civi/Core/Event/HookStyleServiceListenerTest.php b/tests/phpunit/Civi/Core/Event/HookStyleServiceListenerTest.php new file mode 100644 index 000000000000..4e5154316cd0 --- /dev/null +++ b/tests/phpunit/Civi/Core/Event/HookStyleServiceListenerTest.php @@ -0,0 +1,81 @@ +useCustomContainer(function (ContainerBuilder $container) use ($rand) { + $container->register('test.hssvlt', HookStyleServiceListenerTestExample::class) + ->addArgument($rand) + ->addTag('event_subscriber') + ->setPublic(TRUE); + }); + + $d = \Civi::dispatcher(); + + // Baseline + $this->assertEquals([], HookStyleServiceListenerTestExample::$notes); + $this->assertEquals($changeMe, $rand); + + // First call - instantiate and run + $d->dispatch('hook_civicrm_hssvlt', GenericHookEvent::create(['foo' => &$changeMe])); + $this->assertEquals($changeMe, 1 + $rand); + $this->assertEquals(["construct($rand)", "fired($rand)"], HookStyleServiceListenerTestExample::$notes); + + // Second call - reuse and run + $d->dispatch('hook_civicrm_hssvlt', GenericHookEvent::create(['foo' => &$changeMe])); + $this->assertEquals($changeMe, 2 + $rand); + $this->assertEquals(["construct($rand)", "fired($rand)", "fired(" . ($rand + 1) . ")"], HookStyleServiceListenerTestExample::$notes); + } + + /** + * Create and activate a custom service-container. + * + * @param callable $callback + * Callback function which will modify the container. + * function(ContainerBuilder $container) + */ + protected function useCustomContainer(callable $callback) { + $container = (new Container())->createContainer(); + $callback($container); + $container->compile(); + Container::useContainer($container); + } + +} + +class HookStyleServiceListenerTestExample implements HookInterface { + + /** + * Free-form list of strings. + * + * @var array + */ + public static $notes = []; + + public function __construct($rand) { + self::$notes[] = "construct($rand)"; + } + + public function hook_civicrm_hssvlt(&$foo) { + self::$notes[] = "fired({$foo})"; + $foo++; + } + +}