<?php
namespace App\Service\Listeners;
use http\Message;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\SerializerInterface;
class RequestListener
{
private $maxSize;
private $serializer;
public function __construct(int $maxSize, SerializerInterface $serializer)
{
$this->maxSize = $maxSize;
$this->serializer = $serializer;
}
private function formatBytes($bytes, ?int $decimals = 2): string {
// Define units in order of size
$units = ['B', 'K', 'M', 'G'];
// Check if the size is 0
if ($bytes == 0) {
return '0 B';
}
// Calculate the appropriate unit
$factor = floor((strlen($bytes) - 1) / 3);
$formattedSize = $bytes / pow(1024, $factor);
// Return formatted size with the appropriate unit
return round($formattedSize, $decimals) . '' . $units[$factor];
}
private function convertToBytes($value) {
// Trim whitespace from the value
$value = trim($value);
// Get the last character, which represents the unit (e.g., K, M, G)
$unit = strtoupper(substr($value, -1));
// Convert the numeric part to an integer
$value = (int) $value;
// Determine the multiplier based on the unit and convert to bytes
switch ($unit) {
case 'G':
$value *= 1024 * 1024 * 1024; // Convert gigabytes to bytes
break;
case 'M':
$value *= 1024 * 1024; // Convert megabytes to bytes
break;
case 'K':
$value *= 1024; // Convert kilobytes to bytes
break;
}
// Return the value in bytes
return $value;
}
public function onKernelRequest(RequestEvent $event)
{
if (!$event->isMasterRequest() || $event->getRequest()->getMethod() !== 'POST') {
return;
}
$contentLength = $_SERVER['CONTENT_LENGTH'] ?? 0;
if ($contentLength > $this->maxSize) {
$maxFileSize = ini_get('upload_max_filesize');
$sendFile = $this->formatBytes($contentLength);
// JSON formatında hata mesajı hazırlıyoruz
$data = [
// "message" => "The file size limit has been exceeded. Please upload a smaller file. allowed $maxFileSize, tryed $sendFile ",
"message" => "The file size limit has been exceeded. Please upload a smaller file. Allowed: $maxFileSize, but attempted: $sendFile",
"severity" => "warning"
];
$json = $this->serializer->serialize($data, 'json', [
'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS
]);
// 413 (Request Entity Too Large) hata kodu ile JSON yanıtı döndürüyoruz
$response = new JsonResponse( $json, Response::HTTP_REQUEST_ENTITY_TOO_LARGE, [], true);
$event->setResponse($response);
}
}
}