Skip to content

Commit

Permalink
API Introduce promise resolution middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Damian Mooyman committed Oct 26, 2017
1 parent f9b9e98 commit c020061
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
1 change: 1 addition & 0 deletions _config/requestprocessors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ SilverStripe\Core\Injector\Injector:
SessionMiddleware: '%$SilverStripe\Control\Middleware\SessionMiddleware'
RequestProcessorMiddleware: '%$SilverStripe\Control\RequestProcessor'
FlushMiddleware: '%$SilverStripe\Control\Middleware\FlushMiddleware'
EventsMiddleware: '%$SilverStripe\Control\Middleware\RegisteredEventsMiddleware'
SilverStripe\Control\Middleware\AllowedHostsMiddleware:
properties:
AllowedHosts: '`SS_ALLOWED_HOSTS`'
Expand Down
80 changes: 80 additions & 0 deletions src/Control/Middleware/RegisteredEventsMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

namespace SilverStripe\Control\Middleware;

use InvalidArgumentException;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Injector\Injectable;

/**
* Allows events to be registered and passed through middleware.
* Useful for event registered prior to the beginning of a middleware chain.
*/
class RegisteredEventsMiddleware implements HTTPMiddleware
{
use Injectable;

/**
* List of callable events
*
* @var array
*/
protected $events = [];

/**
* Register event
*
* @param callable $event Callback to invoke. This callback will be passed the request object,
* but will not be able to invoke subsequent handlers or events.
* @param string|null $name Optional name for this event
*/
public function registerEvent($event, $name = null)
{
if ($name) {
$this->events[$name] = $event;
} else {
$this->events[] = $event;
}
}

/**
* Check if a named event is registered
*
* @param string $name
* @return bool
*/
public function hasEvent($name)
{
return !is_numeric($name) && isset($this->events[$name]);
}

/**
* Unregister a named event
*
* @param string $name
*/
public function unregisterEvent($name)
{
if (is_numeric($name)) {
throw new InvalidArgumentException("Only named events can be unregistered");
}
unset($this->events[$name]);
}

/**
* Generate response for the given request
*
* @param HTTPRequest $request
* @param callable $delegate
* @return HTTPResponse
*/
public function process(HTTPRequest $request, callable $delegate)
{
// Invoke all registered events
foreach ($this->events as $event) {
$event($request);
}
return $delegate($request);
}
}

0 comments on commit c020061

Please sign in to comment.