1
0
mirror of https://github.com/flarum/core.git synced 2025-08-07 17:07:19 +02:00

add callback and invokable class + tests

This commit is contained in:
Ian Morland
2023-10-11 12:14:59 +01:00
parent 79493e44d8
commit 198229b0a9
2 changed files with 158 additions and 29 deletions

View File

@@ -13,17 +13,36 @@ use Flarum\Extension\Extension;
use Flarum\Extension\ExtensionManager; use Flarum\Extension\ExtensionManager;
use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Container\Container;
/**
* The Conditional extender allows developers to conditionally apply other extenders
* based on either boolean values or results from callable functions.
*
* This is useful for applying extenders only if certain conditions are met,
* such as the presence of an enabled extension or a specific configuration setting.
*
* @package Flarum\Extend
*/
class Conditional implements ExtenderInterface class Conditional implements ExtenderInterface
{ {
/** /**
* An array of conditions and their associated extenders.
*
* Each entry should have:
* - 'condition': a boolean or callable that should return a boolean.
* - 'extenders': an array of extenders, a callable returning an array of extenders, or an invokable class string.
*
* @var array<array{condition: bool|callable, extenders: ExtenderInterface[]}> * @var array<array{condition: bool|callable, extenders: ExtenderInterface[]}>
*/ */
protected $conditions = []; protected $conditions = [];
/** /**
* @param ExtenderInterface[] $extenders * Apply extenders only if a specific extension is enabled.
*
* @param string $extensionId The ID of the extension.
* @param ExtenderInterface[]|callable|string $extenders An array of extenders, a callable returning an array of extenders, or an invokable class string.
* @return self
*/ */
public function whenExtensionEnabled(string $extensionId, array $extenders): self public function whenExtensionEnabled(string $extensionId, $extenders): self
{ {
return $this->when(function (ExtensionManager $extensions) use ($extensionId) { return $this->when(function (ExtensionManager $extensions) use ($extensionId) {
return $extensions->isEnabled($extensionId); return $extensions->isEnabled($extensionId);
@@ -31,10 +50,14 @@ class Conditional implements ExtenderInterface
} }
/** /**
* @param bool|callable $condition * Apply extenders based on a condition.
* @param ExtenderInterface[] $extenders *
* @param bool|callable $condition A boolean or callable that should return a boolean.
* If this evaluates to true, the extenders will be applied.
* @param ExtenderInterface[]|callable|string $extenders An array of extenders, a callable returning an array of extenders, or an invokable class string.
* @return self
*/ */
public function when($condition, array $extenders): self public function when($condition, $extenders): self
{ {
$this->conditions[] = [ $this->conditions[] = [
'condition' => $condition, 'condition' => $condition,
@@ -44,6 +67,13 @@ class Conditional implements ExtenderInterface
return $this; return $this;
} }
/**
* Iterates over the conditions and applies the associated extenders if the conditions are met.
*
* @param Container $container
* @param Extension|null $extension
* @return void
*/
public function extend(Container $container, Extension $extension = null) public function extend(Container $container, Extension $extension = null)
{ {
foreach ($this->conditions as $condition) { foreach ($this->conditions as $condition) {
@@ -52,7 +82,15 @@ class Conditional implements ExtenderInterface
} }
if ($condition['condition']) { if ($condition['condition']) {
foreach ($condition['extenders'] as $extender) { $extenders = $condition['extenders'];
if (is_string($extenders)) {
$extenders = $container->call($extenders);
} elseif (is_callable($extenders)) {
$extenders = $container->call($extenders);
}
foreach ($extenders as $extender) {
$extender->extend($container, $extension); $extender->extend($container, $extension);
} }
} }

View File

@@ -12,12 +12,9 @@ namespace Flarum\Tests\integration\extenders;
use Exception; use Exception;
use Flarum\Api\Serializer\ForumSerializer; use Flarum\Api\Serializer\ForumSerializer;
use Flarum\Extend; use Flarum\Extend;
use Flarum\Extend\ExtenderInterface;
use Flarum\Extension\Extension;
use Flarum\Extension\ExtensionManager; use Flarum\Extension\ExtensionManager;
use Flarum\Testing\integration\RetrievesAuthorizedUsers; use Flarum\Testing\integration\RetrievesAuthorizedUsers;
use Flarum\Testing\integration\TestCase; use Flarum\Testing\integration\TestCase;
use Illuminate\Contracts\Container\Container;
class ConditionalTest extends TestCase class ConditionalTest extends TestCase
{ {
@@ -147,7 +144,7 @@ class ConditionalTest extends TestCase
$this->extend( $this->extend(
(new Extend\Conditional()) (new Extend\Conditional())
->when(function (?ExtensionManager $extensions) { ->when(function (?ExtensionManager $extensions) {
if (! $extensions) { if (!$extensions) {
throw new Exception('ExtensionManager not injected'); throw new Exception('ExtensionManager not injected');
} }
}, [ }, [
@@ -164,44 +161,138 @@ class ConditionalTest extends TestCase
} }
/** @test */ /** @test */
public function conditional_does_not_instantiate_extender_if_condition_is_false() public function conditional_does_not_instantiate_extender_if_condition_is_false_using_callable()
{ {
$this->extend( $this->extend(
(new Extend\Conditional()) (new Extend\Conditional())
->when(false, [ ->when(false, TestExtender::class)
new TestExtender()
])
); );
$this->app(); $this->app();
$response = $this->send(
$this->request('GET', '/api', [
'authenticatedAs' => 1,
])
);
$payload = json_decode($response->getBody()->getContents(), true);
$this->assertArrayNotHasKey('customConditionalAttribute', $payload['data']['attributes']);
} }
/** @test */ /** @test */
public function conditional_does_instantiate_extender_if_condition_is_true() public function conditional_does_instantiate_extender_if_condition_is_true_using_callable()
{ {
$this->expectException(Exception::class);
$this->expectExceptionMessage('TestExtender was instantiated!');
$this->extend( $this->extend(
(new Extend\Conditional()) (new Extend\Conditional())
->when(true, [ ->when(true, TestExtender::class)
new TestExtender()
])
); );
$this->app(); $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_callback()
{
$this->extend(
(new Extend\Conditional())
->when(false, function (): array {
return [
(new Extend\ApiSerializer(ForumSerializer::class))
->attributes(function () {
return [
'customConditionalAttribute' => true
];
})
];
})
);
$this->app();
$response = $this->send(
$this->request('GET', '/api', [
'authenticatedAs' => 1,
])
);
$payload = json_decode($response->getBody()->getContents(), true);
$this->assertArrayNotHasKey('customConditionalAttribute', $payload['data']['attributes']);
}
/** @test */
public function conditional_does_instantiate_extender_if_condition_is_true_using_callback()
{
$this->extend(
(new Extend\Conditional())
->when(true, function (): array {
return [
(new Extend\ApiSerializer(ForumSerializer::class))
->attributes(function () {
return [
'customConditionalAttribute' => true
];
})
];
})
);
$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_work_if_extension_is_disabled()
{
$this->extend(
(new Extend\Conditional())
->whenExtensionEnabled('dummy-extension-id', TestExtender::class)
);
$response = $this->send(
$this->request('GET', '/api', [
'authenticatedAs' => 1,
])
);
$payload = json_decode($response->getBody()->getContents(), true);
$this->assertArrayNotHasKey('customConditionalAttribute', $payload['data']['attributes']);
} }
} }
class TestExtender implements ExtenderInterface class TestExtender
{ {
public function __construct() public function __invoke(): array
{ {
throw new Exception('TestExtender was instantiated!'); return [
} (new Extend\ApiSerializer(ForumSerializer::class))
->attributes(function () {
public function extend(Container $container, Extension $extension = null) return [
{ 'customConditionalAttribute' => true
// This method can be left empty for this test. ];
})
];
} }
} }