Lines
80.00%
16 / 20
Methods
50.00%
1 / 2
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| __construct | 100.00% | 3 / 3 | 100.00% | 1 / 1 | 1 | ||
| process | 76.47% | 13 / 17 | 0.00% | 0 / 1 | 4.21 | ||
| 14 | class RequestSizeLimitMiddleware implements MiddlewareInterface | |
| 15 | { | |
| 16 | private const string ERROR_TOO_LARGE = 'requestEntityTooLarge'; | |
| 17 | private int $maxSize; | |
| 18 | private LoggerService $logger; | |
| 19 | public function __construct(LoggerService $logger) | |
| 20 | { | |
| 21 | $this->logger = $logger; | |
| 22 | $config = \App::getRequestLimits(); | |
| 23 | $this->maxSize = $config['maxSize']; | |
| 24 | } | |
| 25 | ||
| 26 | #[\Override] | |
| 27 | public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
| 28 | { | |
| 29 | try { | |
| 30 | $contentLength = $request->getHeaderLine('Content-Length'); | |
| 31 | if ($contentLength === '') { | |
| 32 | return $handler->handle($request); | |
| 33 | } | |
| 34 | $contentLength = (int)$contentLength; | |
| 35 | if ($contentLength > $this->maxSize) { | |
| 36 | $this->logger->logInfo(sprintf('Request too large: %d bytes. URI: %s', $contentLength, $request->getUri())); | |
| 37 | $response = \App::$slim->getResponseFactory()->createResponse(); | |
| 38 | $response = $response->withStatus(ErrorMessages::get(self::ERROR_TOO_LARGE)['statusCode']) | |
| 39 | ->withHeader('Content-Type', 'application/json'); | |
| 40 | $response->getBody()->write(json_encode([ | |
| 41 | 'errors' => [ErrorMessages::get(self::ERROR_TOO_LARGE)] | |
| 42 | ])); | |
| 43 | return $response; | |
| 44 | } | |
| 45 | ||
| 46 | return $handler->handle($request); | |
| 47 | } catch (\Throwable $e) { | |
| 48 | $this->logger->logError($e, $request); | |
| 49 | throw $e; | |
| 50 | } | |
| 51 | } | |
| 52 | } |