blessing-skin-server/app/Services/Filter.php

49 lines
1.1 KiB
PHP
Raw Normal View History

2019-09-03 18:41:19 +08:00
<?php
namespace App\Services;
use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
class Filter
{
protected $listeners = [];
public function add(string $hook, Closure $callback, $priority = 20)
{
if (! isset($this->listeners[$hook])) {
$this->listeners[$hook] = collect();
}
$this->listeners[$hook]->push([
'callback' => $callback,
'priority' => $priority,
]);
}
2019-09-03 23:07:10 +08:00
public function apply(string $hook, $init, $args = [])
2019-09-03 18:41:19 +08:00
{
$listeners = $this->getListeners($hook);
if ($listeners->isNotEmpty()) {
return $this->listeners[$hook]
2019-09-04 19:33:39 +08:00
->sortBy('priority')
2019-09-03 18:41:19 +08:00
->reduce(function ($carry, $item) use ($args) {
return call_user_func($item['callback'], $carry, ...$args);
2019-09-03 23:07:10 +08:00
}, $init);
2019-09-03 18:41:19 +08:00
} else {
2019-09-03 23:07:10 +08:00
return $init;
2019-09-03 18:41:19 +08:00
}
}
public function remove(string $hook)
{
unset($this->listeners[$hook]);
}
public function getListeners(string $hook): Collection
{
return Arr::get($this->listeners, $hook, collect());
}
}