summaryrefslogtreecommitdiff
path: root/src/Server/RequestHandlers/PhpServer.php
blob: 5447f727bfb14b886d4d779f7f07975879d8838a (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
42
43
44
45
<?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')) {
      ob_start();
      try {
        include $documentPath;
      } catch (\Throwable $exception) {
        echo <<<EXCEPTION

        ```
        $exception
        ```

        EXCEPTION;
      }
      $content = ob_get_clean();

      $response->setBody($content);
      $response->setStatusCode(Status::SUCCESS);
      $response->setMeta('text/gemini; charset=utf-8');
    } else {
      return parent::__invoke($response, $request);
    }

    return $response;
  }
}