ClaimedTaskRunner.php
1 month ago
Cli.php
1 month ago
CronCommand.php
1 month ago
DaemonRunner.php
1 month ago
ExecutionLimitOverride.php
1 month ago
ScheduledTaskResolver.php
1 month ago
ScheduledTasksLister.php
1 month ago
TaskAdder.php
1 month ago
TaskCanceller.php
1 month ago
TaskRunner.php
1 month ago
TaskTrigger.php
1 month ago
WorkerTypesCatalog.php
1 month ago
index.php
1 month ago
ExecutionLimitOverride.php
51 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\Cron\CliCommands; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use InvalidArgumentException; |
| 9 | use MailPoet\WP\Functions as WPFunctions; |
| 10 | |
| 11 | /** |
| 12 | * Overrides MailPoet's cron execution limit for the duration of a callback. |
| 13 | * |
| 14 | * The cron machinery enforces a 20-second limit via the `mailpoet_cron_get_execution_limit` |
| 15 | * filter. When running a worker from WP-CLI we usually want it to run to completion, so the |
| 16 | * default is to lift the cap entirely; a caller may instead pass a number of seconds to cap it. |
| 17 | * The filter is always removed afterwards (including on exceptions) so global state never leaks. |
| 18 | */ |
| 19 | class ExecutionLimitOverride { |
| 20 | private WPFunctions $wp; |
| 21 | |
| 22 | public function __construct( |
| 23 | WPFunctions $wp |
| 24 | ) { |
| 25 | $this->wp = $wp; |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * @template T |
| 30 | * @param int|null $seconds Cap in seconds, or null to lift the limit entirely. |
| 31 | * @param callable():T $fn |
| 32 | * @return T |
| 33 | */ |
| 34 | public function overrideDuring(?int $seconds, callable $fn) { |
| 35 | if ($seconds !== null && $seconds < 0) { |
| 36 | throw new InvalidArgumentException(sprintf('Execution limit must be a non-negative number of seconds, got %d.', $seconds)); |
| 37 | } |
| 38 | $limit = $seconds ?? PHP_INT_MAX; |
| 39 | $filter = function () use ($limit) { |
| 40 | return $limit; |
| 41 | }; |
| 42 | |
| 43 | $this->wp->addFilter('mailpoet_cron_get_execution_limit', $filter, PHP_INT_MAX); |
| 44 | try { |
| 45 | return $fn(); |
| 46 | } finally { |
| 47 | $this->wp->removeFilter('mailpoet_cron_get_execution_limit', $filter, PHP_INT_MAX); |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 |