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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- With Action Scheduler as the driver, the handler of an event received the values of its named arguments only: `->with(['order' => 7])` reached it as `[7]`, while WP-Cron gave `['order' => 7]` (#35). Action Scheduler stores the arguments with their keys, and finds an action by them, but runs the hook with `array_values()`. The driver now tells the engine which action is running, and the handlers it attaches (`->call()`, `#[Schedule]`) take the keys back, so both drivers give the same arguments. Nothing stored changes: actions already scheduled are concerned too. A callback attached straight to the hook with `add_action()` still gets what Action Scheduler passes.

## [1.0.2] - 2026-11-23

### Added
Expand Down
14 changes: 14 additions & 0 deletions src/Drivers/ActionSchedulerDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Pollora\Schedule\Contracts\ScheduleDriver;
use Pollora\Schedule\Event;
use Pollora\Schedule\Exceptions\ScheduleException;
use Pollora\Schedule\Support\ActionArguments;

/**
* Schedules through Action Scheduler: its queue, its retries, its Tools ›
Expand Down Expand Up @@ -88,6 +89,19 @@ public function observe(Closure $changed): void
}
}, 10, 1);

// Action Scheduler runs the hook with the values of the arguments only: tell the handlers which keys they had
add_action('action_scheduler_before_execute', function (mixed $id): void {
$action = $this->fetch($id);

if ($action !== null) {
ActionArguments::running((string) $action->get_hook(), (array) $action->get_args());
}
}, 10, 1);

foreach (['action_scheduler_after_execute', 'action_scheduler_failed_execution', 'action_scheduler_execution_ignored'] as $hook) {
add_action($hook, static fn () => ActionArguments::finished(), 10, 0);
}

foreach (['action_scheduler_stored_action', 'action_scheduler_completed_action', 'action_scheduler_failed_action', 'action_scheduler_canceled_action'] as $hook) {
add_action($hook, $report, 10, 1);
}
Expand Down
5 changes: 3 additions & 2 deletions src/ScheduleEngine.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Pollora\Schedule\Drivers\ActionSchedulerDriver;
use Pollora\Schedule\Drivers\WpCronDriver;
use Pollora\Schedule\Exceptions\ScheduleException;
use Pollora\Schedule\Support\ActionArguments;
use Pollora\Schedule\Support\CronIndex;
use Pollora\Schedule\Support\CronInterceptor;
use Psr\Container\ContainerInterface;
Expand Down Expand Up @@ -804,8 +805,8 @@ public function attach(string $hook, string|array|Closure $handler): void

$this->attached[$key] = true;

add_action($hook, function (mixed ...$received) use ($handler): void {
$this->run($handler, $received);
add_action($hook, function (mixed ...$received) use ($hook, $handler): void {
$this->run($handler, ActionArguments::restore($hook, $received));
}, 10, PHP_INT_MAX);
}

Expand Down
61 changes: 61 additions & 0 deletions src/Support/ActionArguments.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

declare(strict_types=1);

namespace Pollora\Schedule\Support;

/**
* Gives a handler the arguments an event was scheduled with, whichever driver runs it.
*
* Action Scheduler keeps the arguments of an action with their keys (it stores them as JSON, and finds an action by
* the same encoding), but runs the hook with `array_values()` of them: `['order' => 7]` reaches the callback as `[7]`.
* WP-Cron keeps the keys. Right before it runs an action of the engine's group, Action Scheduler fires
* `action_scheduler_before_execute`; the driver tells this class which action is running, and the handlers the engine
* attaches take their keys back from it.
*
* Only a call that is what Action Scheduler is running right now is changed: same hook, same number of arguments,
* same values in the same order. Anything else (the hook fired by hand, another plugin's action on the same hook)
* is left as it came.
*/
final class ActionArguments
{
/**
* @var array{hook: string, args: array<int|string, mixed>}|null
*/
private static ?array $running = null;

/**
* An action of the engine's group is about to run.
*
* @param array<int|string, mixed> $args The arguments as the store keeps them
*/
public static function running(string $hook, array $args): void
{
self::$running = ['hook' => $hook, 'args' => $args];
}

/**
* The action that was running is done, failed or was skipped.
*/
public static function finished(): void
{
self::$running = null;
}

/**
* What Action Scheduler passed $hook, with the keys of the running action put back.
*
* @param array<int|string, mixed> $received
* @return array<int|string, mixed>
*/
public static function restore(string $hook, array $received): array
{
$running = self::$running;

if ($running === null || $running['hook'] !== $hook || array_is_list($running['args']) || array_values($running['args']) !== $received) {
return $received;
}

return $running['args'];
}
}
4 changes: 2 additions & 2 deletions tests/Integration/ActionSchedulerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@

ActionScheduler::runner()->run('Pollora integration');

// Action Scheduler passes the values of the arguments, not their names
// Action Scheduler runs the hook with the values only; the handler still gets the arguments it was scheduled with
$ran = RecordingJob::recorded();

expect($ran)->toHaveCount(1)
->and(array_values($ran[0]))->toBe([7])
->and($ran[0])->toBe(['order' => 7])
->and(as_get_scheduled_actions(['hook' => 'pollora_int_as_due', 'status' => ActionScheduler_Store::STATUS_COMPLETE, 'per_page' => -1], 'ids'))->toHaveCount(1)
->and(Cron::entries('pollora_int_as_due'))->toBe([]);
});
6 changes: 5 additions & 1 deletion tests/Unit/ActionSchedulerMutationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,15 @@
});

describe('reporting what happens to its actions', function (): void {
it('listens to the five hooks, first in line, one argument', function (): void {
it('listens to the five hooks, first in line, one argument, and follows the action it runs', function (): void {
$this->driver->observe(fn () => null);

expect($this->hooked)->toBe([
['action_scheduler_deleted_action', 10, 1],
['action_scheduler_before_execute', 10, 1],
['action_scheduler_after_execute', 10, 0],
['action_scheduler_failed_execution', 10, 0],
['action_scheduler_execution_ignored', 10, 0],
['action_scheduler_stored_action', 10, 1],
['action_scheduler_completed_action', 10, 1],
['action_scheduler_failed_action', 10, 1],
Expand Down
163 changes: 163 additions & 0 deletions tests/Unit/NamedArgumentsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
<?php

declare(strict_types=1);

use Brain\Monkey\Functions;
use Pollora\Schedule\Drivers\ActionSchedulerDriver;
use Pollora\Schedule\Event;
use Pollora\Schedule\ScheduleEngine;
use Pollora\Schedule\Support\ActionArguments;

require_once __DIR__.'/../Support/ActionSchedulerFake.php';

/**
* Action Scheduler stores the arguments with their keys and runs the hook with their values only
* (ActionScheduler_Action::execute() calls do_action_ref_array() with array_values()); WP-Cron keeps the keys.
* The handler of an event must receive the same arguments from both.
*/
beforeEach(function (): void {
$this->actions = [];
$this->received = [];

Functions\when('add_filter')->justReturn(true);
Functions\when('remove_filter')->justReturn(true);
Functions\when('add_action')->alias(function (string $hook, callable $callback): bool {
$this->actions[$hook][] = $callback;

return true;
});
Functions\when('_get_cron_array')->justReturn([]);
Functions\when('_set_cron_array')->justReturn(true);
Functions\when('wp_get_schedules')->justReturn([]);
Functions\when('wp_schedule_single_event')->justReturn(true);
Functions\when('wp_next_scheduled')->justReturn(false);
Functions\when('wp_clear_scheduled_hook')->justReturn(0);
Functions\when('wp_unschedule_hook')->justReturn(0);

// What Action Scheduler's queue runner does around an action of the store
$this->runLikeActionScheduler = function (int $id): void {
$action = ActionScheduler_FakeStore::$actions[$id];
$fire = function (string $hook, mixed ...$args): void {
foreach ($this->actions[$hook] ?? [] as $callback) {
$callback(...$args);
}
};

$fire('action_scheduler_before_execute', $id, 'WP Cron');
$fire($action->hook, ...array_values($action->args));
$fire('action_scheduler_after_execute', $id, $action, 'WP Cron');
};

$this->handler = function (array $args = []): void {
$this->received[] = $args;
};
});

it('gives the handler the named arguments under Action Scheduler', function (): void {
$engine = new ScheduleEngine;
$engine->selectDriver(new ActionSchedulerDriver);
$engine->attach('process_order', $this->handler);
$engine->schedule(new Event('process_order', time() + 60, null, ['order' => 7, 'notify' => true]));

($this->runLikeActionScheduler)(1);

expect($this->received)->toBe([['order' => 7, 'notify' => true]]);
});

it('gives the handler the named arguments under WP-Cron, the same as Action Scheduler does', function (): void {
$engine = new ScheduleEngine;
$engine->attach('process_order', $this->handler);

// wp-cron.php runs the hook with the keys: PHP turns them into named arguments of the closure's variadic
foreach ($this->actions['process_order'] as $callback) {
$callback(...['order' => 7, 'notify' => true]);
}

expect($this->received)->toBe([['order' => 7, 'notify' => true]]);
});

it('keeps a positional list as it is under Action Scheduler', function (): void {
$engine = new ScheduleEngine;
$engine->selectDriver(new ActionSchedulerDriver);
$engine->attach('process_order', $this->handler);
$engine->schedule(new Event('process_order', time() + 60, null, [7, 'x']));

($this->runLikeActionScheduler)(1);

expect($this->received)->toBe([[7, 'x']]);
});

it('finds, tells and cancels an event by its named arguments under Action Scheduler', function (): void {
$engine = new ScheduleEngine;
$engine->selectDriver(new ActionSchedulerDriver);
$at = time() + 3600;
$named = ['order' => 7];

expect($engine->place(new Event('process_order', $at, null, $named)))->toBeTrue()
// the same event again is a duplicate, not a second action
->and($engine->place(new Event('process_order', $at, null, $named)))->toBeFalse()
->and($engine->next('process_order', $named))->toBe($at)
// the values alone are another event
->and($engine->next('process_order', [7]))->toBeNull()
->and($engine->cancel('process_order', [7]))->toBe(0)
->and($engine->cancel('process_order', $named))->toBe(1)
->and($engine->next('process_order', $named))->toBeNull();
});

describe('the running action', function (): void {
it('leaves a hook fired by hand alone, once the action is done', function (): void {
ActionArguments::running('process_order', ['order' => 7]);
ActionArguments::finished();

expect(ActionArguments::restore('process_order', [7]))->toBe([7]);
});

it('leaves the arguments of another hook alone', function (): void {
ActionArguments::running('process_order', ['order' => 7]);

expect(ActionArguments::restore('send_digest', [7]))->toBe([7]);

ActionArguments::finished();
});

it('leaves other values alone: another plugin\'s action on the same hook', function (): void {
ActionArguments::running('process_order', ['order' => 7]);

expect(ActionArguments::restore('process_order', [8]))->toBe([8])
->and(ActionArguments::restore('process_order', [7, 'more']))->toBe([7, 'more']);

ActionArguments::finished();
});

it('is cleared when the action fails or is ignored', function (): void {
$engine = new ScheduleEngine;
$engine->selectDriver(new ActionSchedulerDriver);
$engine->schedule(new Event('process_order', time() + 60, null, ['order' => 7]));

foreach (['action_scheduler_failed_execution', 'action_scheduler_execution_ignored'] as $hook) {
foreach ($this->actions['action_scheduler_before_execute'] as $callback) {
$callback(1, 'WP Cron');
}

expect(ActionArguments::restore('process_order', [7]))->toBe(['order' => 7]);

foreach ($this->actions[$hook] as $callback) {
$callback(1, new RuntimeException, 'WP Cron');
}

expect(ActionArguments::restore('process_order', [7]))->toBe([7]);
}
});

it('ignores an action of another group', function (): void {
$engine = new ScheduleEngine;
$engine->selectDriver(new ActionSchedulerDriver);
$id = as_schedule_single_action(time() + 60, 'process_order', ['order' => 7], 'woocommerce');

foreach ($this->actions['action_scheduler_before_execute'] as $callback) {
$callback($id, 'WP Cron');
}

expect(ActionArguments::restore('process_order', [7]))->toBe([7]);
});
});
Loading