From 4c80ba78d37749bdb5a2ff192eff6ab47079faa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20=C5=A0tancl?= Date: Mon, 19 Aug 2019 20:28:20 +0200 Subject: [PATCH] Introduce integration events, drop --- src/TenancyServiceProvider.php | 9 ++----- src/Traits/TenantManagerEvents.php | 42 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 7 deletions(-) diff --git a/src/TenancyServiceProvider.php b/src/TenancyServiceProvider.php index 8534291b..065a0f15 100644 --- a/src/TenancyServiceProvider.php +++ b/src/TenancyServiceProvider.php @@ -59,13 +59,8 @@ class TenancyServiceProvider extends ServiceProvider public function setTelescopeTags() { - $original_callback = Telescope::$tagUsing; - - Telescope::tag(function (\Laravel\Telescope\IncomingEntry $entry) use ($original_callback) { - $tags = []; - if (! \is_null($original_callback)) { - $tags = $original_callback($entry); - } + Telescope::tag(function (\Laravel\Telescope\IncomingEntry $entry) { + $tags = $this->integration('telescope', $entry); if (\in_array('tenancy', request()->route()->middleware())) { $tags = \array_merge($tags, [ diff --git a/src/Traits/TenantManagerEvents.php b/src/Traits/TenantManagerEvents.php index 38e303a0..237f93b9 100644 --- a/src/Traits/TenantManagerEvents.php +++ b/src/Traits/TenantManagerEvents.php @@ -18,6 +18,13 @@ trait TenantManagerEvents 'ended' => [], ]; + /** + * Integration listeners. + * + * @var callable[][] + */ + protected $integrationListeners = []; + /** * Register a listener that will be executed before tenancy is bootstrapped. * @@ -82,4 +89,39 @@ trait TenantManagerEvents return $prevents->merge($listener($this) ?? []); }, collect([])); } + + /** + * Register a callback for an integration event. + * + * @param string $name + * @param callable $callback + * @return void + */ + public function integrationEvent(string $name, callable $callback) + { + if (array_key_exists($name, $this->integrationListeners)) { + $this->integrationListeners[$name][] = $callback; + } else { + $this->integrationListeners[$name] = [$callback]; + } + } + + /** + * Return callbacks for an integration event. + * + * @param string $name + * @param mixed $arguments,... + * @return callable[] + */ + public function integration(string $name, ...$arguments) + { + if ($arguments) { + // If $arguments are supplied, execute all listeners with arguments. + return array_reduce($this->integrationListeners[$name] ?? [], function ($tags, $listener) use ($arguments) { + return array_merge($tags, $listener(...$arguments)); + }, []); + }; + + return $this->integrationListeners[$name]; + } }