| 1 |
<?php |
| 2 |
/** |
| 3 |
* Handles running all terminal/shutdown tasks.. |
| 4 |
* |
| 5 |
* @package SolidWP\Performance |
| 6 |
*/ |
| 7 |
|
| 8 |
declare( strict_types=1 ); |
| 9 |
|
| 10 |
namespace SolidWP\Performance\Shutdown; |
| 11 |
|
| 12 |
use SolidWP\Performance\Shutdown\Contracts\Terminable; |
| 13 |
|
| 14 |
if ( ! defined( 'ABSPATH' ) ) { |
| 15 |
exit; |
| 16 |
} |
| 17 |
|
| 18 |
/** |
| 19 |
* Handles running all terminal/shutdown tasks. |
| 20 |
* |
| 21 |
* @package SolidWP\Performance |
| 22 |
*/ |
| 23 |
final class Shutdown_Handler { |
| 24 |
|
| 25 |
/** |
| 26 |
* The collection of tasks to run on shutdown. |
| 27 |
* |
| 28 |
* @var Terminable[] |
| 29 |
*/ |
| 30 |
private array $collection; |
| 31 |
|
| 32 |
/** |
| 33 |
* @param Terminable ...$collection The collection of tasks to run on shutdown. |
| 34 |
*/ |
| 35 |
public function __construct( Terminable ...$collection ) { |
| 36 |
$this->collection = $collection; |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* If running on PHP-FPM, this will return the request, but continue processing |
| 41 |
* any code after in the same thread, which means it instantly sends the request back |
| 42 |
* to the browser without needing to wait for the code after it to process. |
| 43 |
* |
| 44 |
* Essentially, this is pseudo async/background processor. |
| 45 |
* |
| 46 |
* @action shutdown |
| 47 |
* |
| 48 |
* @return void |
| 49 |
*/ |
| 50 |
public function handle(): void { |
| 51 |
// Return request early, if possible. |
| 52 |
if ( function_exists( 'fastcgi_finish_request' ) ) { |
| 53 |
fastcgi_finish_request(); |
| 54 |
} elseif ( function_exists( 'litespeed_finish_request' ) ) { |
| 55 |
litespeed_finish_request(); |
| 56 |
} |
| 57 |
|
| 58 |
// Process all Terminable tasks. |
| 59 |
foreach ( $this->collection as $task ) { |
| 60 |
$task->terminate(); |
| 61 |
} |
| 62 |
} |
| 63 |
} |
| 64 |
|