Skip to content

Instantly share code, notes, and snippets.

@davidthingsaker
Last active February 1, 2018 19:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidthingsaker/377aeb627420298c408b to your computer and use it in GitHub Desktop.
Save davidthingsaker/377aeb627420298c408b to your computer and use it in GitHub Desktop.
PjaxMiddleware for Laravel Lumen - Modified from Jeffrey Way's L5.1 version
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\DomCrawler\Crawler;
class PjaxMiddleware
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
if (! $request->pjax() || $response->isRedirection()) {
return $response;
}
$this->filterResponse($response, $request->header('X-PJAX-CONTAINER'))
->setUriHeader($response, $request);
return $response;
}
/**
* Prepare the PJAX-specific response content.
*
* @param Response $response
* @param string $container
* @return $this
*/
protected function filterResponse(Response $response, $container)
{
$crawler = new Crawler($response->getContent());
$response->setContent(
$this->makeTitle($crawler) .
$this->fetchContents($crawler, $container)
);
return $this;
}
/**
* Prepare an HTML title tag.
*
* @param Crawler $crawler
* @return string
*/
protected function makeTitle($crawler)
{
$pageTitle = $crawler->filterXPath('descendant-or-self::head/title')->html();
return "<title>{$pageTitle}</title>";
}
/**
* Fetch the PJAX-specific HTML from the response.
*
* @param Crawler $crawler
* @param string $container
* @return string
*/
protected function fetchContents($crawler, $container)
{
$container = ltrim($container, '#');
$content = $crawler->filterXPath('//div[@id = "'. $container .'"]');
if (! $content->count()) {
abort(422);
}
return $content->html();
}
/**
* Set the PJAX-URL header to the current uri.
*
* @param Response $response
* @param Request $request
*/
protected function setUriHeader(Response $response, Request $request)
{
$response->header(
'X-PJAX-URL', $request->getRequestUri()
);
}
}
@davidthingsaker
Copy link
Author

Modified for Lumen from @JeffreyWay's original L5.1 version which can be found here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment