Tweak Filters API

This commit is contained in:
Pig Fang 2019-09-03 23:07:10 +08:00
parent 3264e376cb
commit 1e625f75bf
4 changed files with 8 additions and 12 deletions

View File

@ -132,7 +132,7 @@ class PlayerController extends Controller
$dispatcher->dispatch('player.renaming', [$player, $newName]);
$can = $filter->apply('can_rename_player', [$player, $newName]);
$can = $filter->apply('user_can_rename_player', true, [$player, $newName]);
if ($can instanceof Rejection) {
return json($can->getReason(), 1);
}

View File

@ -22,21 +22,17 @@ class Filter
]);
}
public function apply(string $hook, array $payload)
public function apply(string $hook, $init, $args = [])
{
$listeners = $this->getListeners($hook);
if ($listeners->isNotEmpty()) {
$value = $payload[0];
unset($payload[0]);
$args = array_values($payload);
return $this->listeners[$hook]
->sortByDesc('priority')
->reduce(function ($carry, $item) use ($args) {
return call_user_func($item['callback'], $carry, ...$args);
}, $value);
}, $init);
} else {
return $payload[0];
return $init;
}
}

View File

@ -192,7 +192,7 @@ class PlayerControllerTest extends TestCase
// Rejected by filter
$filter = resolve(Filter::class);
$pid = $player->pid;
$filter->add('can_rename_player', function ($player, $newName) {
$filter->add('user_can_rename_player', function ($can, $player, $newName) {
$this->assertEquals('new', $newName);
return new Rejection('rejected');
});
@ -202,7 +202,7 @@ class PlayerControllerTest extends TestCase
'code' => 1,
'message' => 'rejected',
]);
$filter->remove('can_rename_player');
$filter->remove('user_can_rename_player');
// Success
Event::fake();

View File

@ -17,7 +17,7 @@ class FilterTest extends TestCase
public function testApply()
{
$filter = new Filter();
$this->assertEquals('value', $filter->apply('hook', ['value', 'add']));
$this->assertEquals('value', $filter->apply('hook', 'value', ['add']));
$filter->add('hook', function ($value, $addition) {
$this->assertEquals('add', $addition);
@ -29,7 +29,7 @@ class FilterTest extends TestCase
$filter->add('hook', function ($value) {
return $value.'_high';
}, 30);
$this->assertEquals('value_high_medium_low', $filter->apply('hook', ['value', 'add']));
$this->assertEquals('value_high_medium_low', $filter->apply('hook', 'value', ['add']));
}
public function testRemove()