summaryrefslogtreecommitdiff
path: root/src/HookManager.php
blob: 215ff5827ef8f4360f8f3b3a8cd29e85a8810294 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?php

namespace FlatFileForms;

class HookManager
{
  private array $actions = [];
  private array $filters = [];

  public function addAction(string $name, callable $function, int $priority = 10): void
  {
    $this->actions[$name][$priority][] = compact('name', 'function', 'priority');
  }

  public function addFilter(string $name, callable $function, int $priority = 10): void
  {
    $this->filters[$name][$priority][] = compact('name', 'function', 'priority');
  }

  public function doAction(string $name, mixed ...$arguments): void
  {
    foreach ($this->actions[$name] ?? [] as $actions) {
      foreach ($actions as $action) {
        call_user_func_array($action['function'], $arguments);
      }
    }
  }

  public function applyFilter(string $name, mixed $value, mixed ...$arguments): mixed
  {
    // set $value as first argument
    array_unshift($arguments, $value);

    foreach ($this->filters[$name] ?? [] as $filters) {
      foreach ($filters as $filter) {
        $value = call_user_func_array($filter['function'], $arguments);
      }
    }

    return $value;
  }
}