summaryrefslogtreecommitdiff
path: root/src/Server/RequestHandlers/PhpServer.php
blob: c3ded4d8936a35f8a0af79f021f63c93cdc24dfd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php

namespace GeminiFoundation\Server\RequestHandlers;

use GeminiFoundation\Request;
use GeminiFoundation\Response;
use GeminiFoundation\Status;

class PhpServer extends DocumentServer
{
  public function __invoke(Response $response, Request $request): Response
  {
    $requestPath = rtrim(urldecode($request->getPath()), '/');
    $filePath = $this->documentRoot . $requestPath;

    $documentPath = $filePath;
    if (! is_file($documentPath)) {
      $documentPath = $filePath . '/' . $this->indexFile;
    }

    if (is_file($documentPath) && str_ends_with($documentPath, '.php')) {
      try {
        ob_start();
        include $documentPath;
        $content = ob_get_clean();

        $response->setStatusCode(Status::SUCCESS);
        $response->setBody($content);
        $response->setMeta('text/gemini; charset=utf-8');
      } catch (\Throwable $exception) {
        $response->setStatusCode(Status::PERMANENT_FAILURE);
        $response->setMeta($exception);
      }

    } else {
      return parent::__invoke($response, $request);
    }

    return $response;
  }
}