Skip to content
2 changes: 1 addition & 1 deletion .harness.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"framework"
],
"ratchet": {
"phpstan_level": 6,
"phpstan_level": 7,
"phpstan_baseline": 0,
"coverage": 93.05,
"type_coverage": 99.66,
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ All notable changes to `pollora/hook` are documented in this file.

### Fixed

- Registering an invokable object (`Action::add('init', new Handler)`) without an argument count threw a `TypeError`, and a static method written as a string (`'Handler::run'`) threw `CallbackAnalysisFailedException`: the parameters were counted with `ReflectionFunction`, which reads neither. They are now read from the object's `__invoke()` and from the named static method.
- An asynchronous handler whose descriptor names a private or protected method was retried as many times as `tries` allowed, each attempt failing the same way with `The handler of … is not callable`. Resolving the descriptor now fails at once with an `UnresolvableHandler` that says the method is not public.
- An asynchronous handler whose descriptor names a private or protected method was retried as many times as `tries` allowed, each attempt failing the same way with `The handler of … is not callable`. Resolving the descriptor now fails at once with an `UnresolvableHandler` that says the method is not public.
- Registering an invokable object (`Action::add('init', new Handler)`) without an argument count threw a `TypeError`, and a static method written as a string (`'Handler::run'`) threw `CallbackAnalysisFailedException`: the parameters were counted with `ReflectionFunction`, which reads neither. They are now read from the object's `__invoke()` and from the named static method.

Expand Down
2 changes: 1 addition & 1 deletion phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ includes:
- vendor/pollora/harness/presets/phpstan/base.neon

parameters:
level: 6
level: 7
paths:
- src
- tests
Expand Down
2 changes: 1 addition & 1 deletion src/Async/AsyncContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
* @param string $hook Hook that fired
* @param \DateTimeImmutable $dispatchedAt Trigger date
* @param int $attempt Attempt number, from 1
* @param array<string, mixed> $captured Values recorded at trigger time
* @param array<int|string, mixed> $captured Values recorded at trigger time
*/
public function __construct(
public int $userId,
Expand Down
6 changes: 3 additions & 3 deletions src/Async/AsyncDispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function __construct(
) {}

/**
* @param array<int, mixed> $arguments Hook arguments, as WordPress passed them
* @param array<int|string, mixed> $arguments Hook arguments, as WordPress passed them (named when a caller named them)
*/
public function dispatch(QueuedHandler $handler, array $arguments): void
{
Expand Down Expand Up @@ -117,8 +117,8 @@ public static function origin(): array
/**
* Run the capture callback of the registration, or the handler class's capture() method.
*
* @param array<int, mixed> $arguments
* @return array<string, mixed>
* @param array<int|string, mixed> $arguments
* @return array<int|string, mixed>
*/
private function capture(QueuedHandler $handler, array $arguments): array
{
Expand Down
4 changes: 2 additions & 2 deletions src/Async/AsyncPayload.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
* @param int $priority Priority of the registration
* @param array<int|string, mixed> $arguments Normalized hook arguments, see ArgumentNormalizer
* @param array{userId: int, blogId: int, locale: string, dispatchedAt: string} $origin Request that fired the hook
* @param array<string, mixed> $captured Normalized values recorded at trigger time
* @param array<int|string, mixed> $captured Normalized values recorded at trigger time
* @param int $attempt Attempt number, from 1
* @param int $tries Number of attempts allowed
* @param bool $keepMissing Run with null in place of a referenced object that no longer exists
Expand Down Expand Up @@ -163,7 +163,7 @@ public function retryDelay(int $failedAttempt): int
/**
* The context handed to the handler, with the captured values rebuilt.
*
* @param array<string, mixed> $captured Denormalized captured values
* @param array<int|string, mixed> $captured Denormalized captured values
*/
public function context(array $captured = []): AsyncContext
{
Expand Down
2 changes: 1 addition & 1 deletion src/Async/QueuedHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ final class QueuedHandler
* @param int $registeredArgs Argument count of the original registration
* @param int $acceptedArgs Hook arguments the handler takes, AsyncContext left out
* @param PendingAsync $options Options, read when the hook fires
* @param callable|null $defaultCapture The handler class's public capture() method, used when capture() is not called
* @param callable|array{object, string}|null $defaultCapture The handler class's public capture() method, used when capture() is not called
*/
public function __construct(
public readonly string $hook,
Expand Down
3 changes: 2 additions & 1 deletion src/Async/Recovery.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,15 @@ public static function run(): void
*/
public static function recover(): int
{
/** @var \wpdb|null $wpdb The database, null before WordPress has loaded it */
global $wpdb;

if (! is_object($wpdb)) {
return 0;
}

$rows = $wpdb->get_results($wpdb->prepare(
"SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s LIMIT %d",
"SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s LIMIT %d", // @phpstan-ignore argument.type (only the table name, which no placeholder can stand for before WordPress 6.2's %i, is interpolated; every value goes through a placeholder)
$wpdb->esc_like(PayloadStore::OPTION_PREFIX).'%',
self::BATCH,
), 'ARRAY_A');
Expand Down
3 changes: 2 additions & 1 deletion src/Async/UniqueLock.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,15 @@ public static function release(string $key): void
*/
public static function prune(int $limit = 500): int
{
/** @var \wpdb|null $wpdb The database, null before WordPress has loaded it */
global $wpdb;

if (! is_object($wpdb)) {
return 0;
}

$names = $wpdb->get_col($wpdb->prepare(
"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND CAST(option_value AS UNSIGNED) < %d LIMIT %d",
"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND CAST(option_value AS UNSIGNED) < %d LIMIT %d", // @phpstan-ignore argument.type (only the table name, which no placeholder can stand for before WordPress 6.2's %i, is interpolated; every value goes through a placeholder)
$wpdb->esc_like(self::OPTION_PREFIX).'%',
time(),
$limit,
Expand Down
20 changes: 13 additions & 7 deletions src/Domain/Service/AbstractHook.php
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ protected function resolveCallback(string $hook, callable|string|array $callback
* Instantiate a class and resolve its method dynamically.
*
* @param string $hook The hook name
* @param string $className The class name
* @param class-string $className The class name
* @param int|null $acceptedArgs Optional. Number of arguments (auto-detected if null)
* @return array{callable: array{object, string}, args: int} Resolved class method callback and argument count
*
Expand Down Expand Up @@ -426,19 +426,24 @@ protected function addHookEvent(string $hook, callable|string|array $callback, i
*/
protected function replaceTrackedCallback(string $hook, int $priority, callable|string|array $current, callable|string|array $replacement, int $acceptedArgs, callable|string|array|null $handler): void
{
foreach ($this->hooks[$hook] ?? [] as $index => $item) {
$registrations = $this->hooks[$hook] ?? [];

foreach ($registrations as $index => $item) {
if ($item['priority'] !== $priority || $item['callback'] !== $current) {
continue;
}

$this->hooks[$hook][$index]['callback'] = $replacement;
$this->hooks[$hook][$index]['args'] = $acceptedArgs;
unset($this->hooks[$hook][$index]['handler']);
$item['callback'] = $replacement;
$item['args'] = $acceptedArgs;
unset($item['handler']);

if ($handler !== null) {
$this->hooks[$hook][$index]['handler'] = $handler;
$item['handler'] = $handler;
}

$registrations[$index] = $item;
$this->hooks[$hook] = $registrations;

return;
}
}
Expand Down Expand Up @@ -479,7 +484,8 @@ private function countParameters(callable|array $callback): int
// An invokable object: its __invoke() method is what WordPress calls
$reflection = new \ReflectionMethod($callback, '__invoke');
} else {
$reflection = new \ReflectionFunction($callback);
// A closure or a function name
$reflection = new \ReflectionFunction(\Closure::fromCallable($callback));
}

return $reflection->getNumberOfParameters();
Expand Down
8 changes: 4 additions & 4 deletions tests/Stubs/wordpress.php
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ function wp_stub_wpdb(): object
{
public string $options = 'wp_options';

/** @var list<array{query: string, args: list<mixed>}> Every query prepared */
/** @var list<array{query: string, args: array<int|string, mixed>}> Every query prepared */
public array $queries = [];

/** @var list<string> The output format asked of each get_results() call */
Expand All @@ -349,7 +349,7 @@ public function esc_like(string $text): string
}

/**
* @return array{query: string, args: list<mixed>}
* @return array{query: string, args: array<int|string, mixed>}
*/
public function prepare(string $query, mixed ...$args): array
{
Expand All @@ -359,7 +359,7 @@ public function prepare(string $query, mixed ...$args): array
}

/**
* @param array{query: string, args: list<mixed>} $prepared
* @param array{query: string, args: array<int|string, mixed>} $prepared
* @return list<array{option_name: string, option_value: mixed}>
*/
public function get_results(array $prepared, string $output): array
Expand All @@ -380,7 +380,7 @@ public function get_results(array $prepared, string $output): array
/**
* Answers the expired-lock query: prefix, time, limit.
*
* @param array{query: string, args: list<mixed>} $prepared
* @param array{query: string, args: array<int|string, mixed>} $prepared
* @return list<string>
*/
public function get_col(array $prepared): array
Expand Down
4 changes: 3 additions & 1 deletion tests/Unit/Async/ActionSchedulerDriverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,9 @@ function runScheduledActions(): void

$cronMessage = $GLOBALS['wp_cron_events'][0]['args'][0];
$actionMessage = $GLOBALS['as_actions'][0]['args'][0];
$long = new AsyncPayload(...[...array_diff_key((array) AsyncPayload::fromJson($actionMessage), ['id' => 1]), 'id' => '11111111-2222-4333-8444-555555555555']);
$longData = json_decode($actionMessage, true, flags: JSON_THROW_ON_ERROR);
$longData['id'] = '11111111-2222-4333-8444-555555555555';
$long = AsyncPayload::fromJson(json_encode($longData, JSON_THROW_ON_ERROR));
PayloadStore::store($long);
$GLOBALS['wp_cron_events'] = [];
RecordingHandler::$calls = [];
Expand Down
2 changes: 1 addition & 1 deletion tests/Unit/Async/ArgumentNormalizerEdgeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ final class NormalizerEdgeMutableDate extends DateTime {}
$GLOBALS['wp_objects'] = [];
$this->normalizer = new ArgumentNormalizer;
$this->roundTrip = fn (array $arguments, bool $keepMissing = false): array => $this->normalizer->denormalize(
json_decode(json_encode($this->normalizer->normalize($arguments)), true),
json_decode(json_encode($this->normalizer->normalize($arguments), JSON_THROW_ON_ERROR), true),
$keepMissing,
);
});
Expand Down
4 changes: 2 additions & 2 deletions tests/Unit/Async/ArgumentNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
$GLOBALS['wp_objects'] = [];
$this->normalizer = new ArgumentNormalizer;
$this->roundTrip = fn (array $arguments, bool $keepMissing = false): array => $this->normalizer->denormalize(
json_decode(json_encode($this->normalizer->normalize($arguments), JSON_PRESERVE_ZERO_FRACTION), true),
json_decode(json_encode($this->normalizer->normalize($arguments), JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR), true),
$keepMissing,
);
});
Expand Down Expand Up @@ -121,7 +121,7 @@ public function supports(object $object): bool

public function reference(object $object): array
{
return ['key' => $object['key']];
return ['key' => $object instanceof ArrayObject ? $object['key'] : null];
}

public function resolve(array $reference): object
Expand Down
8 changes: 4 additions & 4 deletions tests/Unit/Async/AsyncPayloadEdgeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function edgePayload(array $overrides = []): AsyncPayload
$data['origin'][$key] = $value;
}

expect(fn () => AsyncPayload::fromJson(json_encode($data)))
expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR)))
->toThrow(InvalidPayload::class, "'origin.{$key}'");
})->with([
'no userId' => ['userId', null, true],
Expand All @@ -72,7 +72,7 @@ function edgePayload(array $overrides = []): AsyncPayload
$data = json_decode(edgePayload()->toJson(), true);
unset($data['origin']['blogId']);

expect(fn () => AsyncPayload::fromJson(json_encode($data)))
expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR)))
->toThrow(InvalidPayload::class, "The asynchronous payload field 'origin.blogId' is missing or invalid.");
});
});
Expand Down Expand Up @@ -119,13 +119,13 @@ function edgePayload(array $overrides = []): AsyncPayload
$data = json_decode(edgePayload()->toJson(), true);
$data['backoff'] = [0, 5];

expect(AsyncPayload::fromJson(json_encode($data))->backoff)->toBe([0, 5]);
expect(AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR))->backoff)->toBe([0, 5]);
});

it('refuses a delay of minus one', function (): void {
$data = json_decode(edgePayload()->toJson(), true);
$data['backoff'] = [-1];

expect(fn () => AsyncPayload::fromJson(json_encode($data)))->toThrow(InvalidPayload::class, "'backoff'");
expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR)))->toThrow(InvalidPayload::class, "'backoff'");
});
});
6 changes: 3 additions & 3 deletions tests/Unit/Async/AsyncPayloadTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ function makeAsyncPayload(array $overrides = []): AsyncPayload
$data[$field] = $value;
}

expect(fn () => AsyncPayload::fromJson(json_encode($data)))->toThrow(InvalidPayload::class, "'{$reported}'");
expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR)))->toThrow(InvalidPayload::class, "'{$reported}'");
})->with([
['handler', null, 'handler'],
['priority', '10', 'priority'],
Expand All @@ -94,7 +94,7 @@ function makeAsyncPayload(array $overrides = []): AsyncPayload
$data = json_decode(makeAsyncPayload()->toJson(), true);
unset($data['driver'], $data['queue'], $data['asUser'], $data['backoff']);

$payload = AsyncPayload::fromJson(json_encode($data));
$payload = AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR));

expect($payload->driver)->toBeNull()
->and($payload->queue)->toBeNull()
Expand All @@ -107,7 +107,7 @@ function makeAsyncPayload(array $overrides = []): AsyncPayload
$data = json_decode(makeAsyncPayload()->toJson(), true);
$data['backoff'] = $backoff;

expect(fn () => AsyncPayload::fromJson(json_encode($data)))->toThrow(InvalidPayload::class, "'backoff'");
expect(fn () => AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR)))->toThrow(InvalidPayload::class, "'backoff'");
})->with([
'negative' => [[10, -5]],
'not a list' => [['a' => 10]],
Expand Down
4 changes: 3 additions & 1 deletion tests/Unit/Async/CallableDescriptorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,9 @@ public function resolve(string $className): object

$callable = (new CallableDescriptor($resolver))->resolve(InvoiceHandler::class.'@send');

expect($callable[0]->source)->toBe('container');
$target = is_array($callable) ? $callable[0] : null;

expect($target instanceof InvoiceHandler ? $target->source : null)->toBe('container');
});

it('resolves a static method without instantiating', function (): void {
Expand Down
4 changes: 3 additions & 1 deletion tests/Unit/Async/RunnerAndDispatcherEdgeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,8 @@ public function resolve(string $class): object
$action->setCallbackResolver($resolver);
$action->add('init', $class);

expect($action->callbacks('init')[0]['callback'][0])->toBe($instance);
$registered = $action->callbacks('init')[0]['callback'] ?? null;

expect(is_array($registered) ? $registered[0] : null)->toBe($instance);
});
});
10 changes: 5 additions & 5 deletions tests/Unit/Async/StorageAndRecoveryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -75,23 +75,23 @@ public function esc_like(string $text): string
}

/**
* @return array{query: string, args: list<mixed>}
* @return array{query: string, args: array<int|string, mixed>}
*/
public function prepare(string $query, mixed ...$args): array
{
return ['query' => $query, 'args' => $args];
}

/**
* @param array{query: string, args: list<mixed>} $prepared
* @param array{query: string, args: array<int|string, mixed>} $prepared
*/
public function get_results(array $prepared, string $output): mixed
{
return $this->rows;
}

/**
* @param array{query: string, args: list<mixed>} $prepared
* @param array{query: string, args: array<int|string, mixed>} $prepared
*/
public function get_col(array $prepared): mixed
{
Expand Down Expand Up @@ -382,13 +382,13 @@ function executionEventsOf(): array
$lengthWith = function (int $padding): int {
$payload = storagePayload(['arguments' => [str_repeat('a', $padding)]]);

return strlen(json_encode([$payload->toJson()]));
return strlen(json_encode([$payload->toJson()], JSON_THROW_ON_ERROR));
};
$base = $lengthWith(0);
$atLimit = storagePayload(['arguments' => [str_repeat('a', ScheduledDriver::MAX_ARGUMENTS_LENGTH - $base)]]);
$beyond = storagePayload(['arguments' => [str_repeat('a', ScheduledDriver::MAX_ARGUMENTS_LENGTH - $base + 1)]]);

expect(strlen(json_encode([$atLimit->toJson()])))->toBe(ScheduledDriver::MAX_ARGUMENTS_LENGTH);
expect(strlen(json_encode([$atLimit->toJson()], JSON_THROW_ON_ERROR)))->toBe(ScheduledDriver::MAX_ARGUMENTS_LENGTH);

ScheduledDriver::actionScheduler()->dispatch($atLimit);
ScheduledDriver::actionScheduler()->dispatch($beyond);
Expand Down
2 changes: 1 addition & 1 deletion tests/Unit/Async/UniqueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -174,5 +174,5 @@ function uniqueLocks(): array
))->toJson(), true);
unset($data['uniqueKey']);

expect(AsyncPayload::fromJson(json_encode($data))->uniqueKey)->toBeNull();
expect(AsyncPayload::fromJson(json_encode($data, JSON_THROW_ON_ERROR))->uniqueKey)->toBeNull();
});
2 changes: 2 additions & 0 deletions tests/Unit/Domain/Service/AbstractHookTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ public function handle(string $value): string
// Create a class that has a method matching the hook name pattern
$className = 'TestHookClass_'.uniqid();
eval(sprintf('class %s { public function myHook($a) { return $a; } }', $className));
assert(class_exists($className));

$this->hook->add('my_hook', $className);

Expand Down Expand Up @@ -141,6 +142,7 @@ public function myHook(): void {}
it('falls back to direct instantiation when no resolver is set', function (): void {
$className = 'DirectInstantiationTest_'.uniqid();
eval(sprintf('class %s { public function myHook() {} }', $className));
assert(class_exists($className));

// No resolver set
$this->hook->add('my_hook', $className);
Expand Down
Loading
Loading