<?php
namespace Koselig\Routing;
use Illuminate\Http\Request;
use Illuminate\Routing\Route;
use Koselig\Models\Post;
use Koselig\Support\Wordpress;
use ReflectionFunction;
class PostsRoute extends Route
{
public function __construct($methods, $action)
{
if (!get_option('page_for_posts')) {
trigger_error('Attempted to define a posts route when the posts page isn\'t set. Set it in the Reading Settings in Wordpress.', E_USER_NOTICE);
}
parent::__construct($methods, wp_make_link_relative(get_permalink(get_option('page_for_posts'))) ?: '/posts', $action);
}
public function matches(Request $request, $includingMethod = true)
{
return query()->isPostsPage ?? false;
}
protected function runCallable()
{
$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();
}
}