Lines 100.00% 14 / 14
Methods 100.00% 3 / 3
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 process 100.00% 11 / 11 100.00% 1 / 1 3
 isMaintenanceEnabled 100.00% 1 / 1 100.00% 1 / 1 2
 isSourceCacheWarmup 100.00% 2 / 2 100.00% 1 / 1 1
13class MaintenanceMiddleware implements MiddlewareInterface
14{
15    private const int HTTP_UNAVAILABLE = 503;
16    private const string ERROR_UNAVAILABLE = 'serviceUnavailable';
17    #[\Override]
18    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
19    {
20        if ($this->isMaintenanceEnabled() && !$this->isSourceCacheWarmup($request)) {
21            $error = ErrorMessages::get(self::ERROR_UNAVAILABLE);
22
23            $response = \App::$slim->getResponseFactory()->createResponse();
24            $response = $response->withStatus(self::HTTP_UNAVAILABLE)
25                ->withHeader('Content-Type', 'application/json; charset=utf-8');
26
27            $responseBody = json_encode([
28                'errors' => [$error]
29            ]);
30            $response->getBody()->write($responseBody);
31            return $response;
32        }
33
34        return $handler->handle($request);
35    }
36
37    /**
38     * The class constant is fixed when config.php loads. Tests and a later
39     * Application::initialize() update the static property from the same env.
40     */
41    private function isMaintenanceEnabled(): bool
42    {
43        return \App::MAINTENANCE_MODE_ENABLED || \App::$MAINTENANCE_MODE_ENABLED;
44    }
45
46    /**
47     * Helm upgrades warm this route while maintenance mode is on.
48     * Match the route with or without the public path prefix.
49     */
50    private function isSourceCacheWarmup(ServerRequestInterface $request): bool
51    {
52        $path = rtrim($request->getUri()->getPath(), '/');
53
54        return str_ends_with($path, '/source-cache/warmup');
55    }
56}