Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@

### Unreleased

* [BREAKING]: Handler factory functions now take HandlerFactoryArgs instead of LoggerInterface, this allows us to
also pass the request, to allow for simple routing to different handlers.
* [BREAKING]: Added strict types and array shapes throughout.
* [BREAKING]: FactoryFunction::call() no longer accepts or passes arguments to the callable.
* [Internal] Bump dev dependencies
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ project alongside code that uses a different framework).
```php
<?php
// index.php
use \Psr\Http\Message\ServerRequestInterface;
use \Psr\Log\LoggerInterface;

require_once(__DIR__.'/../vendor/autoload.php');

// *NO CODE HERE*
Expand Down Expand Up @@ -60,13 +63,14 @@ require_once(__DIR__.'/../vendor/autoload.php');
// requires.
//
// The only service / dependency that microframework provides to your code is the Logger - this is passed to
// your factory function for you to use as required.
handler_factory: fn(\Psr\Log\LoggerInterface $logger) => new class implements Ingenerator\MicroFramework\RequestHandler {
// your factory function for you to use as required. The HandlerFactoryArgs class also provides the request,
// to allow you to return different handlers based on the request (e.g. for simple routing).
handler_factory: fn(Ingenerator\MicroFramework\HandlerFactoryArgs $args) => new class($args->logger) implements Ingenerator\MicroFramework\RequestHandler {

// If you wish to write log entries from your own code, capture the logger as a constructor argument.
public function __construct(private readonly $logger) {}

public function handle(\Psr\Http\Message\ServerRequestInterface $request): \Psr\Http\Message\ResponseInterface {
public function handle(ServerRequestInterface $request): \Psr\Http\Message\ResponseInterface {
// Do whatever you want with the request here.
// Microframework does not provide any routing - if you need to handle different requests with different
// code, it is up to you to dispatch them appropriately.
Expand Down
17 changes: 17 additions & 0 deletions src/HandlerFactoryArgs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Ingenerator\MicroFramework;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;

final readonly class HandlerFactoryArgs
{
public function __construct(
public LoggerInterface $logger,
public ServerRequestInterface $request,
) {
}
}
18 changes: 16 additions & 2 deletions src/MicroFramework.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public static function throwingErrorHandler(int $code, string $error, ?string $f
* Executes a request.
*
* @param callable():LoggerProvider $logger_provider_factory function that returns a LoggerProvider to get/create a suitable logger
* @param callable(LoggerInterface $logger):RequestHandler $handler_factory function that returns a class containing the application code
* @param callable(HandlerFactoryArgs $args):RequestHandler $handler_factory function that returns a class containing the application code
* @param callable():ServerRequestInterface|null $request_factory callable that provides a ServerRequest - defaults to guzzle/psr7's ServerRequest::fromGlobals()
* @param int|float|null $start_hr_time the hrtime() at the start of the request - ideally captured as the very first thing in index.php. Used for logging latency
* @param string $default_timezone default timezone to set before execution
Expand Down Expand Up @@ -77,7 +77,8 @@ public function execute(
: ServerRequest::fromGlobals();

// Hand off to the application for execution
$response = FactoryFunction::call(fn () => $handler_factory($logger), RequestHandler::class)
$response = $this
->createRequestHandler($handler_factory, $logger, $request)
->handle($request);

// Render the application result
Expand All @@ -102,6 +103,19 @@ public function execute(
}
}

/**
* @param callable(HandlerFactoryArgs $args):RequestHandler $handler_factory
*/
private function createRequestHandler(callable $handler_factory, LoggerInterface $logger, ServerRequestInterface $request): RequestHandler
{
$args = new HandlerFactoryArgs(
logger: $logger,
request: $request
);

return FactoryFunction::call(fn () => $handler_factory($args), RequestHandler::class);
}

private function resetOutputBuffersAssertingNoOutput(): void
{
if (headers_sent($file, $line)) {
Expand Down
1 change: 1 addition & 0 deletions test/blackbox/BaseBlackboxTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ protected static function provisionDynamicHandlerFactoryWithDefaultBootstrap(str
<?php
use GuzzleHttp\Psr7\Response;
use Ingenerator\MicroFramework\DefaultStackdriverLoggerProvider;
use Ingenerator\MicroFramework\HandlerFactoryArgs;
use Ingenerator\MicroFramework\MicroFramework;
use Ingenerator\MicroFramework\RequestHandler;
use Psr\Http\Message\ResponseInterface;
Expand Down
10 changes: 5 additions & 5 deletions test/blackbox/ErrorHandlingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public static function provider_error_handling(): Iterator
];
yield 'factory does not return a handler instance' => [
<<<'PHP'
fn (LoggerInterface $logger) => new class extends stdClass {
fn () => new class extends stdClass {
public function handle(ServerRequestInterface $request): ResponseInterface
{
return new Response(200, body: 'Should not get here, it is the wrong instance type');
Expand All @@ -36,12 +36,12 @@ public function handle(ServerRequestInterface $request): ResponseInterface
];
yield 'factory references undefined class' => [
<<<'PHP'
fn (LoggerInterface $logger) => new \My\Undefined\RequestHandlerClass()
fn () => new \My\Undefined\RequestHandlerClass()
PHP,
];
yield 'uncaught exception during handler' => [
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
throw new \RuntimeException('You broke it');
Expand All @@ -51,7 +51,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface
];
yield 'php error in handler' => [
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
$map = ['no' => 'thing'];
Expand All @@ -62,7 +62,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface
];
yield 'TypeError in handler' => [
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
return $this->doThings($request);
Expand Down
2 changes: 1 addition & 1 deletion test/blackbox/HttpHeadersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static function setUpBeforeClass(): void
parent::setUpBeforeClass();
self::$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP_WRAP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
$body = \Ingenerator\PHPUtils\StringEncoding\JSON::decodeArray($request->getBody()->getContents());
Expand Down
4 changes: 2 additions & 2 deletions test/blackbox/HttpResponseCodesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static function setUpBeforeClass(): void
parent::setUpBeforeClass();
self::$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
$query = $request->getQueryParams();
Expand Down Expand Up @@ -44,7 +44,7 @@ public function testItCanOptionallyUseCustomStatusCodesIfReasonPhraseProvided():
{
$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
$query = $request->getQueryParams();
Expand Down
10 changes: 5 additions & 5 deletions test/blackbox/OutputBufferingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public function testItReturnsErrorWithoutOutputIfAnyCodeWritesOutputDuringReques
{
$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
echo "You did something";
Expand All @@ -71,7 +71,7 @@ public function testItTreatsAsErrorIfUserLeavesOutputBuffersOpen(): void
{
$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
ob_start();
Expand All @@ -93,7 +93,7 @@ public function testItTreatsAsErrorIfUserFlushesOutputBuffers(): void
{
$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
ob_start();
Expand All @@ -116,7 +116,7 @@ public function testItDoesNotTreatAsErrorIfUserHandlesOutputBufferingCorrectly()
{
$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
ob_start();
Expand All @@ -138,7 +138,7 @@ public function testItDoesNotTreatAsErrorIfUserHandlesOutputBufferingCorrectlyWi
{
$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
ob_start();
Expand Down
4 changes: 2 additions & 2 deletions test/blackbox/RequestParsingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public static function setUpBeforeClass(): void
parent::setUpBeforeClass();
self::$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
return new Response(
Expand Down Expand Up @@ -186,7 +186,7 @@ public function testItCanDetectIncomingUrlsWhenRewriting(): void
{
$handler_url = self::provisionDynamicHandlerFactoryWithDefaultBootstrap(
<<<'PHP'
fn (LoggerInterface $logger) => new class implements RequestHandler {
fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
return new Response(
Expand Down
33 changes: 16 additions & 17 deletions test/blackbox/StackdriverLoggingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ public function testItLogsRequestsOnCompletionInStackdriverFormat(): void
use Ingenerator\MicroFramework\RequestHandler;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;

require_once('/var/www/vendor/autoload.php');

Expand All @@ -37,7 +36,7 @@ public function testItLogsRequestsOnCompletionInStackdriverFormat(): void
service_name: 'my-service',
version_file_path: $version_file_path,
),
handler_factory: fn (LoggerInterface $logger) => new class implements RequestHandler {
handler_factory: fn () => new class implements RequestHandler {
public function handle(ServerRequestInterface $request): ResponseInterface
{
return new Response(203, body: 'OK');
Expand Down Expand Up @@ -113,7 +112,6 @@ public function testItLogsUncaughtExceptionsAndRequestInStackdriverFormat(): voi
use Ingenerator\MicroFramework\RequestHandler;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;

require_once('/var/www/vendor/autoload.php');
// Note: defining this as a named class to make log output assertions easier to follow (anonymous classes
Expand All @@ -131,7 +129,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface
service_name: 'my-service',
version_file_path: '/var/www/version.php',
),
handler_factory: fn (LoggerInterface $logger) => new MyHandler($logger),
handler_factory: fn () => new MyHandler(),
);
PHP,
);
Expand Down Expand Up @@ -184,7 +182,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface
$this->assertSame(
[
'severity' => 'EMERGENCY',
'message' => 'Uncaught RuntimeException: I broke at /var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php:/var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php',
'message' => 'Uncaught RuntimeException: I broke at /var/www/htdocs/dynamic/StackdriverLoggingTest_2e73de2f8da6828bd4b6026ac94ec76b0432a401/index.php:/var/www/htdocs/dynamic/StackdriverLoggingTest_2e73de2f8da6828bd4b6026ac94ec76b0432a401/index.php',
'@ingenType' => 'app',
'serviceContext' => [
'service' => 'my-service',
Expand All @@ -199,7 +197,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface
],
'reportLocation' => [
'filePath' => '/var/www/vendor/ingenerator/microframework/src/MicroFramework.php',
'lineNumber' => 152,
'lineNumber' => 166,
'functionName' => 'Ingenerator\MicroFramework\MicroFramework->logUncaughtException',
],
],
Expand All @@ -208,25 +206,25 @@ public function handle(ServerRequestInterface $request): ResponseInterface
'class' => 'RuntimeException',
'msg' => 'I broke',
'code' => 0,
'file' => '/var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php',
'line' => 17,
'file' => '/var/www/htdocs/dynamic/StackdriverLoggingTest_2e73de2f8da6828bd4b6026ac94ec76b0432a401/index.php',
'line' => 16,
'trace' => <<<'TEXT'
#0 /var/www/vendor/ingenerator/microframework/src/MicroFramework.php(81): MyHandler->handle()
#1 /var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php(21): Ingenerator\MicroFramework\MicroFramework->execute()
#0 /var/www/vendor/ingenerator/microframework/src/MicroFramework.php(82): MyHandler->handle()
#1 /var/www/htdocs/dynamic/StackdriverLoggingTest_2e73de2f8da6828bd4b6026ac94ec76b0432a401/index.php(20): Ingenerator\MicroFramework\MicroFramework->execute()
#2 {main}
TEXT,
],
'logging.googleapis.com/sourceLocation' => [
'file' => '/var/www/vendor/ingenerator/microframework/src/MicroFramework.php',
'line' => 152,
'line' => 166,
'function' => 'Ingenerator\MicroFramework\MicroFramework->logUncaughtException',
],
'@type' => 'type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent',
'stack_trace' => <<<'TEXT'
PHP Warning: RuntimeException: I broke in /var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php:17
PHP Warning: RuntimeException: I broke in /var/www/htdocs/dynamic/StackdriverLoggingTest_2e73de2f8da6828bd4b6026ac94ec76b0432a401/index.php:16
Stack trace:
#0 /var/www/vendor/ingenerator/microframework/src/MicroFramework.php(81): MyHandler->handle()
#1 /var/www/htdocs/dynamic/StackdriverLoggingTest_54a57cd69e4889f9c6cfdde12f4607f1461dec3e/index.php(21): Ingenerator\MicroFramework\MicroFramework->execute()
#0 /var/www/vendor/ingenerator/microframework/src/MicroFramework.php(82): MyHandler->handle()
#1 /var/www/htdocs/dynamic/StackdriverLoggingTest_2e73de2f8da6828bd4b6026ac94ec76b0432a401/index.php(20): Ingenerator\MicroFramework\MicroFramework->execute()
#2 {main}
TEXT,
],
Expand Down Expand Up @@ -266,6 +264,7 @@ public function testItOutputsCustomAppLogsInStackdriverFormat(): void
<?php
use GuzzleHttp\Psr7\Response;
use Ingenerator\MicroFramework\DefaultStackdriverLoggerProvider;
use Ingenerator\MicroFramework\HandlerFactoryArgs;
use Ingenerator\MicroFramework\MicroFramework;
use Ingenerator\MicroFramework\RequestHandler;
use Psr\Http\Message\ResponseInterface;
Expand All @@ -291,7 +290,7 @@ public function handle(ServerRequestInterface $request): ResponseInterface
service_name: 'my-service',
version_file_path: '/var/www/version.php',
),
handler_factory: fn (LoggerInterface $logger) => new MyHandler($logger),
handler_factory: fn (HandlerFactoryArgs $args) => new MyHandler($args->logger),
);
PHP,
);
Expand Down Expand Up @@ -360,8 +359,8 @@ public function handle(ServerRequestInterface $request): ResponseInterface
],
// 'logging.googleapis.com/trace' => '66991537308e16.07573263',
'logging.googleapis.com/sourceLocation' => [
'file' => '/var/www/htdocs/dynamic/StackdriverLoggingTest_0ba32a129fbc45c0d394a95f76d7bdf405c84692/index.php',
'line' => 18,
'file' => '/var/www/htdocs/dynamic/StackdriverLoggingTest_b6ab65fbb5280907f86e2517cfa96312e743341d/index.php',
'line' => 19,
'function' => 'MyHandler->handle',
],
'custom_context' => [
Expand Down
Loading
Loading