Browse Source

Added Event::until method.

Allows execution of events up until first non-null response is returned.

Signed-off-by: Taylor Otwell <taylorotwell@gmail.com>
Taylor Otwell 12 years ago
parent
commit
48b8791c62
1 changed files with 35 additions and 2 deletions
  1. 35 2
      laravel/event.php

+ 35 - 2
laravel/event.php

@@ -85,6 +85,20 @@ class Event {
 		return head(static::fire($event, $parameters));
 		return head(static::fire($event, $parameters));
 	}
 	}
 
 
+	/**
+	 * Fire an event and return the the first response.
+	 *
+	 * Execution will be halted after the first valid response is found.
+	 *
+	 * @param  string  $event
+	 * @param  array   $parameters
+	 * @return mixed
+	 */
+	public static function until($event, $parameters = array())
+	{
+		return static::fire($event, $parameters, true);
+	}
+
 	/**
 	/**
 	 * Fire an event so that all listeners are called.
 	 * Fire an event so that all listeners are called.
 	 *
 	 *
@@ -98,17 +112,36 @@ class Event {
 	 *
 	 *
 	 * @param  string  $event
 	 * @param  string  $event
 	 * @param  array   $parameters
 	 * @param  array   $parameters
+	 * @param  bool    $halt
 	 * @return array
 	 * @return array
 	 */
 	 */
-	public static function fire($event, $parameters = array())
+	public static function fire($event, $parameters = array(), $halt = false)
 	{
 	{
 		$responses = array();
 		$responses = array();
 
 
+		$parameters = (array) $parameters;
+
+		// If the event has listeners, we will simply iterate through them and call
+		// each listener, passing in the parameters. We will add the responses to
+		// an array of event responses and return the array.
 		if (static::listeners($event))
 		if (static::listeners($event))
 		{
 		{
 			foreach (static::$events[$event] as $callback)
 			foreach (static::$events[$event] as $callback)
 			{
 			{
-				$responses[] = call_user_func_array($callback, (array) $parameters);
+				$response = call_user_func_array($callback, $parameters);
+
+				// If the event is set to halt, we will return the first response
+				// that is not null. This allows the developer to easily stack
+				// events but still get the first valid response.
+				if ($halt and ! is_null($response))
+				{
+					return $response;
+				}
+
+				// After the handler has been called, we'll add the response to
+				// an array of responses and return the array to the caller so
+				// all of the responses can be easily examined.
+				$responses[] = $response;
 			}
 			}
 		}
 		}