summaryrefslogtreecommitdiff
path: root/app/Core/Plugin/Hook.php
blob: 4fb5556996efc108b019b7a6be76794ca6f55369 (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php

namespace Core\Plugin;

/**
 * Plugin Hooks Handler
 *
 * @package  plugin
 * @author   Frederic Guillot
 */
class Hook
{
    /**
     * List of hooks
     *
     * @access private
     * @var array
     */
    private $hooks = array();

    /**
     * Bind something on a hook
     *
     * @access public
     * @param  string   $hook
     * @param  mixed    $value
     */
    public function on($hook, $value)
    {
        if (! isset($this->hooks[$hook])) {
            $this->hooks[$hook] = array();
        }

        $this->hooks[$hook][] = $value;
    }

    /**
     * Get all bindings for a hook
     *
     * @access public
     * @param  string  $hook
     * @return array
     */
    public function getListeners($hook)
    {
        return isset($this->hooks[$hook]) ? $this->hooks[$hook] : array();
    }

    /**
     * Merge listener results with input array
     *
     * @access public
     * @param  string  $hook
     * @param  array   $values
     * @param  array   $params
     * @return array
     */
    public function merge($hook, array &$values, array $params = array())
    {
        foreach ($this->getListeners($hook) as $listener) {
            $result = call_user_func_array($listener, $params);

            if (is_array($result) && ! empty($result)) {
                $values = array_merge($values, $result);
            }
        }

        return $values;
    }
}