hooked.php

Event hook dispatch utility
git clone git://git.finwo.net/lib/hooked.php
Log | Files | Refs

Hooked.php (1838B)


      1 <?php
      2 
      3 namespace Finwo\Hooked;
      4 
      5 use Invoker\Invoker;
      6 
      7 abstract class Hooked
      8 {
      9     /**
     10      * @var array
     11      */
     12     protected $hooks = array();
     13 
     14     /**
     15      * @var Invoker
     16      */
     17     protected $invoker;
     18 
     19     protected function getInvoker()
     20     {
     21         if (is_null($this->invoker)) {
     22             $this->invoker = new Invoker();
     23         }
     24         return $this->invoker;
     25     }
     26 
     27     /**
     28      * Add a hook the the element
     29      *
     30      * @param string $key
     31      * @param \Closure $callback
     32      * @return $this|bool
     33      */
     34     public function addHook( $key = '', \Closure $callback = null )
     35     {
     36         // Make sure the key is valid
     37         if (is_string($key)) {
     38             return false;
     39         }
     40 
     41         // Make sure the callback is valid
     42         if (!is_callable($callback)) {
     43             return false;
     44         }
     45 
     46         // Make sure the hook entry exists
     47         if (isset($this->hooks[$key])) {
     48             $this->hooks[$key] = array();
     49         }
     50 
     51         // Store hook
     52         $this->hooks[$key][] = $callback;
     53 
     54         // Return ourselves
     55         return $this;
     56     }
     57 
     58     /**
     59      * Runs all hooks on a certain key
     60      *
     61      * @param  Event  $event
     62      *
     63      * @return Hooked $this
     64      */
     65     protected function dispatch( Event $event )
     66     {
     67         // Pre-define some required stuff
     68         $invoker = $this->getInvoker();
     69         $name    = $event->get('name');
     70 
     71         // Make sure the hook entry exists
     72         if (!isset($this->hooks[$name])) {
     73             $this->hooks[$name] = array();
     74         }
     75 
     76         foreach ($this->hooks[$name] as $hook) {
     77 
     78             // Call the hook
     79             if (!$invoker->call($hook, array_merge(array(
     80                 'event' => $event
     81             )))) {
     82                 // Break propegation if asked to
     83                 break;
     84             }
     85         }
     86 
     87         return $this;
     88     }
     89 }