Skip to content

Instantly share code, notes, and snippets.

@logaretm
Created October 14, 2015 10:58
Show Gist options
  • Save logaretm/06ec672bc75e03f69ecc to your computer and use it in GitHub Desktop.
Save logaretm/06ec672bc75e03f69ecc to your computer and use it in GitHub Desktop.
The pjax middleware Jeffery Way explained on his Pjax Laracasts lesson
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Symfony\Component\DomCrawler\Crawler;
class FilterIfPjax
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
// redirect will fire the middleware again when it comes around, so no need to filter it.
if(!$request->pjax() || $response->isRedirection())
{
return $response;
}
$this->filterResponse($response, $request->header('X-PJAX-CONTAINER'))
->setUriHeader($response, $request);
return $response;
}
/**
* Filters the response by swapping its content with the requested container.
*
* @param Response $response
* @param $container
* @return $this
*/
protected function filterResponse(Response $response, $container)
{
$crawler = new Crawler($response->getContent());
// Combines the title tag with the new content, pjax should identify the new tag title
// and swap it with current (old) title value in the document.
$response->setContent(
$this->makeTitle($crawler) .
$this->fetchContainer($crawler, $container)
);
return $this;
}
/**
* Creates the page title and returns it in a title tag.
*
* @param Crawler $crawler
* @return string
*/
protected function makeTitle(Crawler $crawler)
{
$pageTitle = $crawler->filter('head > title')->html();
return "<title>{$pageTitle}</title>";
}
/**
* Filters and gets the content from the original container.
*
* @param Crawler $crawler
* @param $container
* @return mixed
*/
protected function fetchContainer(Crawler $crawler, $container)
{
$content = $crawler->filter($container);
if(! $content->count())
{
// No content was found.
abort(422);
}
return $content->html();
}
/**
* Updates the URL in the address bar with the new page url.
*
* @param $response
* @param $request
*/
protected function setUriHeader(Response $response, Request $request)
{
$response->header('X-PJAX-URL', $request->getRequestUri());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment