diff --git a/src/RouteCompleteCallback.php b/src/RouteCompleteCallback.php new file mode 100644 index 0000000..4086064 --- /dev/null +++ b/src/RouteCompleteCallback.php @@ -0,0 +1,56 @@ +setCallback($callback); + } + } + + public static function i(callable $callback = null) + { + return new static($callback); + } + + public function match(Context $context): bool + { + if($this->_condition instanceof Condition) + { + return $this->_condition->match($context); + } + return true; + } + + public function setCondition(Condition $condition) + { + $this->_condition = $condition; + return $this; + } + + public function setCallback(callable $callback) + { + $this->_callback = $callback; + return $this; + } + + public function complete(Context $context) + { + $func = $this->_callback; + if(is_callable($func)) + { + return $func($context); + } + return null; + } + +} diff --git a/tests/RouteCompleteCallbackTest.php b/tests/RouteCompleteCallbackTest.php new file mode 100644 index 0000000..94c2ac9 --- /dev/null +++ b/tests/RouteCompleteCallbackTest.php @@ -0,0 +1,73 @@ +meta()->set('callback', 1); + } + ) + )->setHandler($handler) + ))->handle($ctx); + + $this->assertEquals(1, $ctx->meta()->get('callback')); + + try + { + (new TestSingleRouteSelector( + Route::with( + RouteCompleteCallback::i( + function (Context $ctx) { + $ctx->meta()->set('callback', 2); + } + )->setCondition(RequestCondition::i()->domain('invalid')) + )->setHandler($handler) + ))->handle($ctx); + } + catch(Exception $e) + { + } + $this->assertEquals(1, $ctx->meta()->get('callback')); + + (new TestSingleRouteSelector( + Route::with( + RouteCompleteCallback::i( + function (Context $ctx) { + $ctx->meta()->set('callback', 3); + } + )->setCondition(RequestCondition::i()->domain('test')) + )->setHandler($handler) + ))->handle($ctx); + + $this->assertEquals(3, $ctx->meta()->get('callback')); + + (new TestSingleRouteSelector(Route::with(RouteCompleteCallback::i())->setHandler($handler)))->handle($ctx); + $this->assertEquals(3, $ctx->meta()->get('callback')); + } +} diff --git a/tests/Supporting/TestSingleRouteSelector.php b/tests/Supporting/TestSingleRouteSelector.php index 2f76639..ae530eb 100644 --- a/tests/Supporting/TestSingleRouteSelector.php +++ b/tests/Supporting/TestSingleRouteSelector.php @@ -6,6 +6,7 @@ use Packaged\Http\Response; use Packaged\Routing\Handler\FuncHandler; use Packaged\Routing\Handler\Handler; +use Packaged\Routing\Route; use Packaged\Routing\RouteSelector; class TestSingleRouteSelector extends RouteSelector @@ -19,6 +20,11 @@ public function __construct($route = null) protected function _generateRoutes() { + if($this->_route instanceof Route) + { + yield $this->_route; + return null; + } return $this->_route; }