Skip to content

Instantly share code, notes, and snippets.

@alexbilbie
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbilbie/823a7987256556fecfb5 to your computer and use it in GitHub Desktop.
Save alexbilbie/823a7987256556fecfb5 to your computer and use it in GitHub Desktop.
Example StackPHP middleware
<?php
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class EtagMiddleware implements HttpKernelInterface
{
protected $app;
public function __construct(HttpKernelInterface $app)
{
$this->app = $app;
}
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true)
{
// Run the next middleware (or app)
$response = $this->app->handle($request, $type, $catch);
// Calculate the MD5 of the response
$responseEtag = md5($response->getContent());
// Validate request's requirements
if ($request->headers->has('If-None-Match')) {
if ($request->headers->get('If-None-Match') === $responseEtag) {
$response->setContent('');
$response->setStatusCode(304);
}
} elseif ($request->headers->has('If-Match')) {
if ($request->headers->get('If-Match') !== $responseEtag) {
$e = new PreconditionFailedException();
$this->terminate($request, exceptionDecorator($e));
throw $e;
}
}
$response->headers->set('Etag', $responseEtag);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment