Psr7Middlewares\Middleware\ImageTransformer::__invoke PHP Method

__invoke() public method

Execute the middleware.
public __invoke ( Psr\Http\Message\ServerRequestInterface $request, Psr\Http\Message\ResponseInterface $response, callable $next ) : Psr\Http\Message\ResponseInterface
$request Psr\Http\Message\ServerRequestInterface
$response Psr\Http\Message\ResponseInterface
$next callable
return Psr\Http\Message\ResponseInterface
    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);
    }