62 lines
1.8 KiB
PHP
62 lines
1.8 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Phred\Http\Middleware;
|
|
|
|
use Psr\Http\Message\ResponseInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
use Psr\Http\Server\MiddlewareInterface;
|
|
use Psr\Http\Server\RequestHandlerInterface;
|
|
|
|
abstract class Middleware implements MiddlewareInterface
|
|
{
|
|
/** @var array<string, float> */
|
|
protected static array $timings = [];
|
|
|
|
abstract public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface;
|
|
|
|
/**
|
|
* Wrap a handler and measure its execution time.
|
|
*/
|
|
protected function profile(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
|
{
|
|
$start = microtime(true);
|
|
try {
|
|
return $handler->handle($request);
|
|
} finally {
|
|
$duration = microtime(true) - $start;
|
|
self::$timings[static::class] = (self::$timings[static::class] ?? 0) + $duration;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Simple profiler for middleware that don't need to wrap the handler.
|
|
*/
|
|
protected function profileSelf(callable $callback): mixed
|
|
{
|
|
$start = microtime(true);
|
|
try {
|
|
return $callback();
|
|
} finally {
|
|
$duration = microtime(true) - $start;
|
|
self::$timings[static::class] = (self::$timings[static::class] ?? 0) + $duration;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get all recorded timings.
|
|
* @return array<string, float>
|
|
*/
|
|
public static function getTimings(): array
|
|
{
|
|
return self::$timings;
|
|
}
|
|
|
|
protected function json(array $data, int $status = 200): ResponseInterface
|
|
{
|
|
$response = new \Nyholm\Psr7\Response($status, ['Content-Type' => 'application/json']);
|
|
$response->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES));
|
|
return $response;
|
|
}
|
|
}
|