public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
switch (Utils\Helpers::getMimeType($response)) {
case 'image/jpeg':
case 'image/gif':
case 'image/png':
$key = $this->getCacheKey($request);
//Get from the cache
if ($cached = $this->getFromCache($key, $response)) {
return $cached;
}
$info = $this->parsePath($request->getUri()->getPath());
if (!$info) {
break;
}
//Removes the transform info in the path
list($path, $transform) = $info;
$request = $request->withUri($request->getUri()->withPath($path));
$response = $next($request, $response);
//Transform
if ($response->getStatusCode() === 200 && $response->getBody()->getSize()) {
$response = $this->transform($request, $response, $transform);
//Save in the cache
$this->saveIntoCache($key, $response);
}
return $response;
case 'text/html':
$generator = function ($path, $transform) {
$info = pathinfo($path);
if (!isset($this->sizes[$transform])) {
throw new \InvalidArgumentException(sprintf('The image size "%s" is not valid', $transform));
}
return Utils\Helpers::joinPath($info['dirname'], $transform . $info['basename']);
};
$request = self::setAttribute($request, self::KEY_GENERATOR, $generator);
$response = $next($request, $response);
if (!empty($this->clientHints)) {
return $response->withHeader('Accept-CH', implode(',', $this->clientHints));
}
return $response;
}
return $next($request, $response);
}