Skip to content

Instantly share code, notes, and snippets.

@gquemener
Created May 12, 2018 09:45
Show Gist options
  • Save gquemener/bbab91389e0d4656bc6c4c832618e4c5 to your computer and use it in GitHub Desktop.
Save gquemener/bbab91389e0d4656bc6c4c832618e4c5 to your computer and use it in GitHub Desktop.
<?php
declare (strict_types = 1);
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Response;
final class ValidateRequestContentSize implements EventSubscriberInterface
{
private $maxContentLength;
public function __construct(string $max = null)
{
$this->maxContentLength = $this->normalizeMaxSize($max ?? ini_get('post_max_size'));
}
public function onKernelRequest(GetResponseEvent $event): void
{
$request = $event->getRequest();
$contentLength = $request->headers->get('content-length');
if ($this->maxContentLength && $contentLength > $this->maxContentLength) {
$event->setResponse(new Response('', Response::HTTP_REQUEST_ENTITY_TOO_LARGE));
}
}
private function normalizeMaxSize(string $size): ?int
{
if ('' === $size) {
return null;
}
$max = ltrim(strtolower(trim($size)), '+');
if (0 === strpos($max, '0x')) {
$max = intval($max, 16);
} elseif (0 === strpos($max, '0')) {
$max = intval($max, 8);
} else {
$max = (int) $max;
}
switch (substr($size, -1)) {
case 't': $max *= 1024;
// no break
case 'g': $max *= 1024;
// no break
case 'm': $max *= 1024;
// no break
case 'k': $max *= 1024;
}
return $max;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment