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
28 changes: 28 additions & 0 deletions src/Dispatch/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand All @@ -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 {
Expand Down
7 changes: 7 additions & 0 deletions test/phpunit/ApplicationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
18 changes: 15 additions & 3 deletions test/phpunit/Debug/SentryLogHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
}
11 changes: 10 additions & 1 deletion test/phpunit/Debug/SentryReporterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, array{?string, string, ?string}> */
Expand Down
73 changes: 73 additions & 0 deletions test/phpunit/Dispatch/DispatcherTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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) {
Expand Down