diff --git a/src/Dispatch/Dispatcher.php b/src/Dispatch/Dispatcher.php index 39bceb7f..44e8ba2a 100644 --- a/src/Dispatch/Dispatcher.php +++ b/src/Dispatch/Dispatcher.php @@ -71,6 +71,7 @@ class Dispatcher { private LogicStreamHandler $logicStreamHandler; private Input $input; private Response $response; + private int|false $nativeStatusCode; private Container $serviceContainer; private Injector $injector; @@ -127,6 +128,7 @@ public function __construct( // Next, we set up the response and service container, which will be used by the // Dispatcher dependencies throughout the request-response lifecycle. $this->response = $this->setupResponse(); + $this->nativeStatusCode = http_response_code(); $containerFactory = new ContainerFactory(); $this->serviceContainer = $containerFactory->create($this->config); $this->injector = new Injector($this->serviceContainer); @@ -570,10 +572,14 @@ private function handleLogicExecution( $extraArgs[$legacyElementClass] = $component; } + $this->updateResponse(); + foreach($this->logicExecutor->invoke($logicAssembly, "go_before", $extraArgs) as $functionReference) { $this->recordLogicExecution($functionReference); } + $this->updateResponse(); + $doAction = $input ? $this->getDoActionForLogic($input, $component) : null; if($doAction) { $doName = "do_" . str_replace("-", "_", $doAction); @@ -583,13 +589,35 @@ private function handleLogicExecution( } } + $this->updateResponse(); + foreach($this->logicExecutor->invoke($logicAssembly, "go", $extraArgs) as $functionReference) { $this->recordLogicExecution($functionReference); } + $this->updateResponse(); + foreach($this->logicExecutor->invoke($logicAssembly, "go_after", $extraArgs) as $functionReference) { $this->recordLogicExecution($functionReference); } + + $this->updateResponse(); + } + + private function updateResponse():void { + $nativeStatusCode = http_response_code(); + + // Only import changes made during this request, not PHP's initial status. + if($nativeStatusCode === false || $this->nativeStatusCode === $nativeStatusCode) { + return; + } + $this->nativeStatusCode = $nativeStatusCode; + if($this->response->getStatusCode() === $nativeStatusCode) { + return; + } + + $this->response = $this->response->withStatus($nativeStatusCode); + $this->serviceContainer->set($this->response); } private function getDoActionForLogic(Input $input, ?Element $component):?string { diff --git a/test/phpunit/ApplicationTest.php b/test/phpunit/ApplicationTest.php index 3c94f21e..5e794f0c 100644 --- a/test/phpunit/ApplicationTest.php +++ b/test/phpunit/ApplicationTest.php @@ -30,6 +30,13 @@ use PHPUnit\Framework\TestCase; class ApplicationTest extends TestCase { + protected function setUp():void { + parent::setUp(); + $this->resetApplicationLoggerState(); + LogConfig::addHandler(new TestLogHandler()); + $this->setApplicationLoggerConfigured(true); + } + public function testConstruct_appliesConfiguredTimezone():void { $originalTimezone = date_default_timezone_get(); try { diff --git a/test/phpunit/Debug/SentryLogHandlerTest.php b/test/phpunit/Debug/SentryLogHandlerTest.php index 0417240c..6f701547 100644 --- a/test/phpunit/Debug/SentryLogHandlerTest.php +++ b/test/phpunit/Debug/SentryLogHandlerTest.php @@ -164,8 +164,20 @@ public function testDeliveryFailureDoesNotEscapeOrRetry():void { $client->expects(self::once())->method("captureEvent")->willThrowException(new RuntimeException("offline")); $handler = new SentryLogHandler(); $handler->setClient($client); - $handler->handle("ERROR", "Test delivery failure"); - $handler->flush(); - $handler->flush(); + $logFile = tempnam(sys_get_temp_dir(), "sentry-delivery-"); + $originalLog = ini_set("error_log", $logFile); + try { + $handler->handle("ERROR", "Test delivery failure"); + $handler->flush(); + $handler->flush(); + self::assertSame(1, substr_count( + file_get_contents($logFile), + "WebEngine: Sentry log delivery unavailable: ERROR Test delivery failure", + )); + } + finally { + ini_set("error_log", $originalLog); + unlink($logFile); + } } } diff --git a/test/phpunit/Debug/SentryReporterTest.php b/test/phpunit/Debug/SentryReporterTest.php index ff1c003d..2c1f7047 100644 --- a/test/phpunit/Debug/SentryReporterTest.php +++ b/test/phpunit/Debug/SentryReporterTest.php @@ -106,7 +106,16 @@ public function testInitialisationFailureDoesNotEscape():void { public function testCaptureFailureDoesNotEscape():void { $client = self::createMock(ClientInterface::class); $client->expects(self::once())->method("captureException")->willThrowException(new RuntimeException("offline")); - (new SentryReporter($client, new ServerRequest("GET", "/")))->report(new RuntimeException("test")); + $logFile = tempnam(sys_get_temp_dir(), "sentry-capture-"); + $originalLog = ini_set("error_log", $logFile); + try { + (new SentryReporter($client, new ServerRequest("GET", "/")))->report(new RuntimeException("test")); + self::assertStringContainsString("WebEngine: Sentry exception reporting failed.", file_get_contents($logFile)); + } + finally { + ini_set("error_log", $originalLog); + unlink($logFile); + } } /** @return array */ diff --git a/test/phpunit/Dispatch/DispatcherTest.php b/test/phpunit/Dispatch/DispatcherTest.php index 22dfb161..c7987c40 100644 --- a/test/phpunit/Dispatch/DispatcherTest.php +++ b/test/phpunit/Dispatch/DispatcherTest.php @@ -56,6 +56,12 @@ #[AllowMockObjectsWithoutExpectations] class DispatcherTest extends TestCase { + protected function setUp():void { + parent::setUp(); + $this->resetLoggerState(); + LogConfig::addHandler(new TestLogHandler()); + } + protected function tearDown():void { $this->resetLoggerState(); parent::tearDown(); @@ -1335,6 +1341,73 @@ public static function redirectModes():iterable { yield "error response" => [true]; } + #[DataProvider("nativeStatusPhases")] + public function testGenerateResponse_importsNativeStatusChanges(string $phase):void { + $originalStatus = http_response_code(); + http_response_code(StatusCode::OK); + $sut = null; + $logicExecutor = $this->createMock(LogicExecutor::class); + $logicExecutor->method("invoke") + ->willReturnCallback(function(Assembly $assembly, string $name)use($phase, &$sut):\Generator { + if($name === $phase) { + http_response_code(StatusCode::ACCEPTED); + } + elseif(http_response_code() === StatusCode::ACCEPTED) { + $container = $this->getPrivateProperty($sut, "serviceContainer"); + self::assertSame(StatusCode::ACCEPTED, $container->get(Response::class)->getStatusCode()); + } + yield "{$assembly->current()}::$name()"; + }); + + try { + $sut = $this->createDispatcher( + logicAssembly: $this->createAssembly("/tmp/page.php"), + logicExecutor: $logicExecutor, + ); + self::assertSame(StatusCode::ACCEPTED, $sut->generateResponse()->getStatusCode()); + } + finally { + http_response_code($originalStatus ?: StatusCode::OK); + } + } + + public static function nativeStatusPhases():iterable { + yield "before" => ["go_before"]; + yield "main" => ["go"]; + yield "after" => ["go_after"]; + } + + public function testGenerateResponse_preservesResponseWhenNativeStatusChangesToMatch():void { + $originalStatus = http_response_code(); + http_response_code(StatusCode::OK); + $logicExecutor = $this->createMock(LogicExecutor::class); + $logicExecutor->method("invoke") + ->willReturnCallback(function(Assembly $assembly, string $name):\Generator { + if($name === "go") { + http_response_code(StatusCode::ACCEPTED); + } + yield from []; + }); + + try { + $sut = $this->createDispatcher( + logicAssembly: $this->createAssembly("/tmp/page.php"), + logicExecutor: $logicExecutor, + ); + $response = new Response(StatusCode::ACCEPTED); + $this->setPrivateProperty($sut, "response", $response); + $container = $this->getPrivateProperty($sut, "serviceContainer"); + $container->set($response); + + self::assertSame($response, $sut->generateResponse()); + self::assertSame($response, $container->get(Response::class)); + self::assertSame(StatusCode::ACCEPTED, $response->getStatusCode()); + } + finally { + http_response_code($originalStatus ?: StatusCode::OK); + } + } + private function createComponentProcessor(HTMLDocument $viewModel, string ...$names):ViewModelProcessor { $componentList = new LogicAssemblyComponentList(); foreach($names as $name) {