-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathHandler.php
More file actions
69 lines (58 loc) · 2.18 KB
/
Handler.php
File metadata and controls
69 lines (58 loc) · 2.18 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php declare(strict_types=1);
namespace Bref\DevServer;
use Bref\Bref;
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7\Response;
use Nyholm\Psr7Server\ServerRequestCreator;
use Psr\Http\Message\ServerRequestInterface;
use RuntimeException;
use Symfony\Component\Yaml\Yaml;
use Whoops\Handler\PrettyPageHandler;
use Whoops\Run;
/**
* @internal
*/
class Handler
{
public const ASSETS_DIRECTORY_VARIABLE = '_BREF_LOCAL_ASSETS_DIRECTORY';
public function handleRequest(): bool|null
{
$assetsDirectory = getenv(self::ASSETS_DIRECTORY_VARIABLE);
// Serve assets
if (PHP_SAPI === 'cli-server') {
$url = parse_url($_SERVER['REQUEST_URI']);
if (is_file($assetsDirectory . ($url['path'] ?? ''))) return false;
}
$whoops = new Run;
$whoops->pushHandler(new PrettyPageHandler);
$whoops->register();
$container = Bref::getContainer();
$serverlessFile = getcwd() . '/serverless.yml';
if (! file_exists($serverlessFile)) {
throw new RuntimeException('No serverless.yml file was found in the current directory. This dev server needs a serverless.yml to discover the API Gateway routes.');
}
$serverlessConfig = Yaml::parseFile($serverlessFile, Yaml::PARSE_CUSTOM_TAGS);
$router = Router::fromServerlessConfig($serverlessConfig);
$request = $this->requestFromGlobals();
[$handler, $request] = $router->match($request);
$controller = $handler ? $container->get($handler) : new NotFound;
$context = $request->getAttribute('lambda-event')?->getRequestContext();
$response = $controller->handle($request, $context);
if (is_array($response)) {
$response = new Response(200, [], $response['body']);
}
(new ResponseEmitter)->emit($response);
return null;
}
private function requestFromGlobals(): ServerRequestInterface
{
$psr17Factory = new Psr17Factory;
$requestFactory = new ServerRequestCreator(
$psr17Factory,
$psr17Factory,
$psr17Factory,
$psr17Factory
);
return $requestFactory->fromGlobals();
}
}