From 3596d31759dcdacd402d1ac16c5698e17d56d324 Mon Sep 17 00:00:00 2001 From: Jordan Doyle Date: Sat, 15 Oct 2016 15:03:08 +0100 Subject: [PATCH] allow page and template routes to typehint a post --- src/Routing/PageRoute.php | 26 ++++++++++++++++++++++++++ src/Routing/TemplateRoute.php | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/Routing/PageRoute.php b/src/Routing/PageRoute.php index 5641d91..c5a1d88 100644 --- a/src/Routing/PageRoute.php +++ b/src/Routing/PageRoute.php @@ -3,7 +3,9 @@ namespace Koselig\Routing; use Illuminate\Http\Request; use Illuminate\Routing\Route; +use Koselig\Models\Post; use Koselig\Support\Wordpress; +use ReflectionFunction; /** * Single page route, this route is matched when the @@ -24,6 +26,30 @@ class PageRoute extends Route } /** + * Run the route action and return the response. + * + * @return mixed + */ + protected function runCallable() + { + // bind the current post to the parameters of the function + $function = new ReflectionFunction($this->action['uses']); + $params = $function->getParameters(); + + foreach ($params as $param) { + if ($param->getClass() + && ($param->getClass()->isSubclassOf(Post::class) || $param->getClass()->getName() === Post::class)) { + $builder = $param->getClass()->getMethod('query')->invoke(null); + $post = $builder->find(Wordpress::id()); + + $this->setParameter($param->getName(), $post); + } + } + + return parent::runCallable(); + } + + /** * Determine if the route matches given request. * * @param \Illuminate\Http\Request $request diff --git a/src/Routing/TemplateRoute.php b/src/Routing/TemplateRoute.php index 93cb598..9ec26b3 100644 --- a/src/Routing/TemplateRoute.php +++ b/src/Routing/TemplateRoute.php @@ -3,7 +3,9 @@ namespace Koselig\Routing; use Illuminate\Http\Request; use Illuminate\Routing\Route; +use Koselig\Models\Post; use Koselig\Support\Wordpress; +use ReflectionFunction; /** * Template route, this route is matched then the Wordpress @@ -24,6 +26,30 @@ class TemplateRoute extends Route } /** + * Run the route action and return the response. + * + * @return mixed + */ + protected function runCallable() + { + // bind the current post to the parameters of the function + $function = new ReflectionFunction($this->action['uses']); + $params = $function->getParameters(); + + foreach ($params as $param) { + if ($param->getClass() + && ($param->getClass()->isSubclassOf(Post::class) || $param->getClass()->getName() === Post::class)) { + $builder = $param->getClass()->getMethod('query')->invoke(null); + $post = $builder->find(Wordpress::id()); + + $this->setParameter($param->getName(), $post); + } + } + + return parent::runCallable(); + } + + /** * Determine if the route matches given request. * * @param \Illuminate\Http\Request $request -- libgit2 1.7.2