From 8eb56b16cf5670622da41fb00abfca2fdc1f6328 Mon Sep 17 00:00:00 2001 From: IanM <16573496+imorland@users.noreply.github.com> Date: Tue, 12 Nov 2024 09:40:05 +0000 Subject: [PATCH] [1.x] feat: conditional extend whenExtensionDisabled (#4107) * feat: conditional extend whenExtensionDisabled * Apply fixes from StyleCI --------- Co-authored-by: StyleCI Bot --- framework/core/src/Extend/Conditional.php | 14 +++++++++++++ .../integration/extenders/ConditionalTest.php | 21 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/framework/core/src/Extend/Conditional.php b/framework/core/src/Extend/Conditional.php index d0c1d699fe..558c3e5095 100644 --- a/framework/core/src/Extend/Conditional.php +++ b/framework/core/src/Extend/Conditional.php @@ -47,6 +47,20 @@ public function whenExtensionEnabled(string $extensionId, $extenders): self }, $extenders); } + /** + * Apply extenders only if a specific extension is disabled/not installed. + * + * @param string $extensionId The ID of the extension. + * @param ExtenderInterface[]|callable|string $extenders A callable returning an array of extenders, or an invokable class string. + * @return self + */ + public function whenExtensionDisabled(string $extensionId, $extenders): self + { + return $this->when(function (ExtensionManager $extensions) use ($extensionId) { + return ! $extensions->isEnabled($extensionId); + }, $extenders); + } + /** * Apply extenders based on a condition. * diff --git a/framework/core/tests/integration/extenders/ConditionalTest.php b/framework/core/tests/integration/extenders/ConditionalTest.php index 2ee1512073..3c3db37905 100644 --- a/framework/core/tests/integration/extenders/ConditionalTest.php +++ b/framework/core/tests/integration/extenders/ConditionalTest.php @@ -160,6 +160,27 @@ public function conditional_injects_dependencies_to_condition_callable() $this->app(); } + /** @test */ + public function conditional_disabled_extension_not_enabled_applies_extender() + { + $this->extend( + (new Extend\Conditional()) + ->whenExtensionDisabled('flarum-dummy-extension', TestExtender::class) + ); + + $this->app(); + + $response = $this->send( + $this->request('GET', '/api', [ + 'authenticatedAs' => 1, + ]) + ); + + $payload = json_decode($response->getBody()->getContents(), true); + + $this->assertArrayHasKey('customConditionalAttribute', $payload['data']['attributes']); + } + /** @test */ public function conditional_does_not_instantiate_extender_if_condition_is_false_using_callable() {