Skip to content

Commit

Permalink
feat: add defer function for deferred execution
Browse files Browse the repository at this point in the history
  • Loading branch information
SonyPradana committed Jan 3, 2025
1 parent faeab8a commit d4b0975
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/System/Integrate/helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// path aplication

use System\Http\RedirectResponse;
use System\Integrate\Application;
use System\Integrate\Exceptions\ApplicationNotAvailable;
use System\Router\Router;

Expand Down Expand Up @@ -299,9 +300,9 @@ function is_dev(): bool
/**
* Get Application container.
*/
function app(): System\Integrate\Application
function app(): Application
{
$app = System\Integrate\Application::getIntance();
$app = Application::getIntance();
if (null === $app) {
throw new ApplicationNotAvailable();
}
Expand Down Expand Up @@ -415,3 +416,22 @@ function abort(int $code, string $message = '', array $headers = []): void
app()->abort($code, $message, $headers);
}
}

if (false === function_exists('defer')) {
/**
* Terminate application after response send.
*/
function defer(callable $callback): bool
{
if (function_exists('fastcgi_finish_request')
|| function_exists('litespeed_finish_request')
|| false === in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)
) {
Application::getIntance()->registerTerminate($callback);

return true;
}

return false;
}
}
19 changes: 19 additions & 0 deletions tests/Integrate/ApplicationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,25 @@ public function itCanAddCallImediatllyIfApplicationAlredyBooted()
$this->assertEquals($out, 'imediatly call');
}

/** @test */
public function itCanDeferFunctionExecution()
{
$app = new Application('/');
$skip = defer(function () {
echo 'deferred.';
});

if (false === $skip) {
$this->markTestSkipped('skiped if not support defer.');
}

ob_start();
$app->terminate();
$out = ob_get_clean();

$this->assertEquals('deferred.', $out);
}

/** @test */
public function itCanCallDeprecatedMethod()
{
Expand Down

0 comments on commit d4b0975

Please sign in to comment.